[英]Python: fastest way to match keys and values between two dicts
除了迭代每個字典並進行匹配之外,還有什么方法可以做到這一點?
主要問這個問題,看是否有某種有效的方法可以做到這一點而不是循環遍歷。 也許itertools模塊中有一些func可以做到這一點,或者我不知道嗎? 有點像拉鏈? izip?
dict1:
{'command': ('aks',), 'variants': ('common',), 'name': 'oop', 'imports': ('abc', 'efg')}
dict2:
{'exports': <type 'dict'>, 'serialize': <type 'bool'>, 'force': <type 'bool'>, 'name': <type 'str'>, 'build_host': <type 'str'>, 'imports': <type 'list'>, 'logfile_timeout': <type 'int'>, 'update': 'skip_check', 'by_variant': <type 'list'>, 'command': <type 'list'>, 'signature': <type 'str'>, 'variants': 'skip_check'}
預期結果:兩個字典中相同鍵的值的枚舉或字典一起
commands:
(('aks',), <type 'list'>)
variants:
(('common',), 'skip_check')
name:
('oop', <type 'str'>)
imports:
(('abc', 'efg'),<type 'list'>)
我不確定您到底在尋找什么,但這是我能做的最好的事情:
keys = d1.viewkeys() & d2
print zip(map(d1.get, keys), map(d2.get, keys))
產量
[(('abc', 'efg'), <type 'list'>),
(('common',), 'skip_check'),
(('aks',), <type 'list'>),
('oop', <type 'str'>)]
注意:這假定d1
中的鍵全部存在於d2
。
此解決方案適用於大多數版本的Python,而dict.viewkeys
僅適用於Python 2.7(不適用於2.6或3,您必須用dict.keys
代替):
dict1 = {'command': ('aks',), 'variants': ('common',), 'name': 'oop', 'imports': ('abc', 'efg')}
dict2 = {'exports': dict, 'serialize': bool, 'force': bool, 'name': str, 'build_host': str, 'imports': list, 'logfile_timeout': int, 'update': 'skip_check', 'by_variant': list, 'command': list, 'signature': str, 'variants': 'skip_check'}
for key in set(dict1).intersection(dict2):
print(key + ':')
print(dict1[key], dict2[key])
打印:
imports:
(('abc', 'efg'), <type 'list'>)
variants:
(('common',), 'skip_check')
command:
(('aks',), <type 'list'>)
name:
('oop', <type 'str'>)
您可能想要的是將鍵的交集歸類為dict:
intersect_dict= dict((key, [d[key] for d in (dict1, dict2)])
for key in set(dict1).intersection(dict2))
import pprint
pprint.pprint(intersect_dict)
打印:
{'command': [('aks',), <type 'list'>],
'imports': [('abc', 'efg'), <type 'list'>],
'name': ['oop', <type 'str'>],
'variants': [('common',), 'skip_check']}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.