在列表中获取字典,其中键:值对位于另一个字典列表中

时间:2016-02-28 11:52:13

标签: python list dictionary

我有两个字典列表,例如

L1 = [
    {'ID': '1', 'file': 'test1', 'ext': 'txt'},
    {'ID': '2', 'file': 'test2', 'ext': 'txt'},
    {'ID': '3', 'file': 'test3', 'ext': 'py'}
]

L2 = [
    {'file': 'test1', 'ext': 'txt', 'val': '5'},
    {'file': 'test3', 'ext': 'py', 'val': '7'},
    {'file': 'test4', 'ext': 'py', 'val': '8'}
]

我想从L1中提取所有字典,其中'file''ext'的键:值对可以在L2的字典中找到。

在我们的案例中

L = [
    {'ID': '1', 'ext': 'txt', 'file': 'test1'},
    {'ID': '3', 'ext': 'py', 'file': 'test3'}
]

有没有聪明的pythonic方式来做到这一点?

4 个答案:

答案 0 :(得分:4)

您可以使用以下列表理解:

L1 = [
    {'ID':'1','file':'test1','ext':'txt'},
    {'ID':'2','file':'test2','ext':'txt'},
    {'ID':'3','file':'test3','ext':'py'}
]

L2 = [
    {'file':'test1','ext':'txt','val':'5'},
    {'file':'test3','ext':'py','val':'7'},
    {'file':'test4','ext':'py','val':'8'}
]


L = [d1 for d1 in L1 if any(
         d2.get('file') == d1['file'] and d2.get('ext') == d1['ext'] for d2 in L2)]
print(L)

<强>输出

[{'ID': '1', 'ext': 'txt', 'file': 'test1'},
 {'ID': '3', 'ext': 'py', 'file': 'test3'}]

这会迭代d1中的每个字典L1,并且对于每个字典都会测试d1['file']d1['ext']的关键:值对是否存在于任何字典中在L2

答案 1 :(得分:2)

这是一个接受匹配关键参数的通用函数(robust)。

def extract_matching_dictionaries(l1, l2, mk):
    return [d1 for d1 in l1 if all(k in d1 for k in mk) and
            any(all(d1[k] == d2[k] for k in mk) for d2 in l2 if all(k in d2 for k in mk))]

示例:

>>> extract_matching_dictionaries(L1, L2, ['file', 'ext'])
[{'ID': '1', 'ext': 'txt', 'file': 'test1'},
 {'ID': '3', 'ext': 'py', 'file': 'test3'}]

答案 2 :(得分:1)

使用您的输入:

L1 = [
    {'ID': '1', 'file': 'test1', 'ext': 'txt'},
    {'ID': '2', 'file': 'test2', 'ext': 'txt'},
    {'ID': '3', 'file': 'test3', 'ext': 'py'}
]

L2 = [
    {'file': 'test1', 'ext': 'txt', 'val': '5'},
    {'file': 'test3', 'ext': 'py', 'val': '7'},
    {'file': 'test4', 'ext': 'py', 'val': '8'}
]

您可以先在集合中提取file - ext对:

pairs = {(d['file'], d['ext']) for d in L2 for k in d}

并在第二步中过滤它们:

[d for d in L1 if (d['file'], d['ext']) in pairs]

结果:

[{'ID': '1', 'ext': 'txt', 'file': 'test1'},
 {'ID': '3', 'ext': 'py', 'file': 'test3'}]

答案 3 :(得分:1)

#!/usr/bin/python
# -*- coding: utf-8 -*-

L1 = [{'ID': '1', 'file': 'test1', 'ext': 'txt'}, {'ID': '2',
      'file': 'test2', 'ext': 'txt'}, {'ID': '3', 'file': 'test3',
      'ext': 'py'}]

L2 = [{'file': 'test1', 'ext': 'txt', 'val': '5'}, {'file': 'test3',
      'ext': 'py', 'val': '7'}, {'file': 'test4', 'ext': 'py',
      'val': '8'}]

keys = ['file', 'ext']

for each in L1:
    for each1 in L2:
        if each1[keys[0]] == each[keys[0]] and each1[keys[1]] \
== each[keys[1]]:
            print each
相关问题