简体   繁体   English

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

[英]Get dictionaries in a list where the key:value pairs are in another list of dictionaries

I have two lists of dictionaries, eg 我有两个字典列表,例如

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'}
]

I want to extract all dictionaries from L1 where the key:value pairs of 'file' and 'ext' can be found in a dictionary of L2 . 我想从L1中提取所有字典,其中关键字: 'file''ext'值对可以在L2的字典中找到。

In our case 在我们的例子中

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

Is there a smart pythonic way to do this? 有没有一种聪明的pythonic方式来做到这一点?

You could use the following list comprehension: 您可以使用以下列表理解:

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)

Output 产量

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

This iterates over each dictionary d1 in L1 , and for each one tests if both the key:value pairs of d1['file'] and d1['ext'] exist in any of the dictionaries in L2 . 这将遍历L1每个字典d1 ,并且对于每个字典d1 ,测试是否存在L2中的任何字典中的d1['file']d1['ext']的键值对。

Here is a generic function (robust) that will accept match key parameters. 这是一个接受匹配关键参数的通用函数(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))]

Example: 例:

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

Using your input: 使用您的输入:

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'}
]

You can extract the file - ext pairs first in a set: 您可以先在集合中提取file - ext对:

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

and filter them in a second step: 并在第二步中过滤它们:

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

Result: 结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM