在字典列表中查找公用键值对的pythonic方法 [英] pythonic way to find common key value pair among list of dict
本文介绍了在字典列表中查找公用键值对的pythonic方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字典清单。
alljson = [{'EchoTime': 0,
'FlipAngle': 90,
'MRAcquisitionType': '2D',
'MagneticFieldStrength': 3,
'Manufacturer': 'SIEMENS',
'ManufacturerModelName': 'TrioTim',
'RepetitionTime': 2,
'ScanOptions': 'FS',
'ScanningSequence': 'AP',
'SequenceVariant': 'SK',
'TaskName': 'Tom'},
{'EchoTime': 0,
'FlipAngle': 90,
'MRAcquisitionType': '2D',
'MagneticFieldStrength': 3,
'Manufacturer': 'SIEMENS',
'ManufacturerModelName': 'TrioTim',
'RepetitionTime': 2,
'ScanOptions': 'FS',
'ScanningSequence': 'EP',
'SequenceVariant': 'SK',
'TaskName': 'fb'},
{'EchoTime': 0,
'FlipAngle': 90,
'MRAcquisitionType': '2D',
'MagneticFieldStrength': 3,
'Manufacturer': 'SIEMENS',
'ManufacturerModelName': 'TrioTim',
'RepetitionTime': 2,
'ScanOptions': 'FS',
'ScanningSequence': 'EP',
'SequenceVariant': 'HK',
'TaskName': 'Tom-loc'}]
<现在我打算从字典列表中找到所有常见的键值对。
这是最Python的方式。
Now i intend to find all common key value pairs from the list of dict. what would be the most pythonic way to do it.
注意:键和值都应该匹配,并且所有字典中都应存在k:v对
Note: key and value both should match, and k:v pair should exist in all dict
I在此处中尝试了所有建议的解决方案,但给出了值不可散列,所有解决方案均无法完全解决。
I tried all solutions suggested here but given values are non hashable, none of the solution fully works.
有什么建议吗?
推荐答案
将每个字典的项目列表转换为集合,找到集合的交集,然后有选择地将结果转换回字典:
Convert each dictionary's list of items into a set, find the set intersection, and optionally convert the result back to a dictionary:
dict(set.intersection(*[set(d.items()) for d in alljson]))
#{'MRAcquisitionType': '2D', 'FlipAngle': 90, 'RepetitionTime': 2,
# 'ScanOptions': 'FS', 'ManufacturerModelName': 'TrioTim',
# 'Manufacturer': 'SIEMENS', 'SequenceVariant': 'SK', 'EchoTime': 0,
# 'MagneticFieldStrength': 3, 'ScanningSequence': 'EP'}
这篇关于在字典列表中查找公用键值对的pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文