Python 在一个列表中获取字典,其中key:value对位于另一个字典列表中
我有两份字典目录,例如Python 在一个列表中获取字典,其中key:value对位于另一个字典列表中,python,list,dictionary,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': '
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'}
]
有没有一种灵巧的python方法可以做到这一点?您可以使用以下列表:
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'}]
这将迭代
L1
中的每个字典d1
,并针对每个字典测试d1['file']
和d1['ext']
的键:值对是否都存在于L2
中的任何字典中,这里有一个通用函数(健壮)可以接受匹配的键参数
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'}]
使用您的输入:
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'}
]
您可以在集合中首先提取文件
-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'}]
到目前为止你尝试了什么?