[英]How to find common occurrences of dictionary in a list of list of dictionaries
我有一個字典列表,我想找到兩個列表之間的常用字典。
例如:
dict_list = [[{'1' : 1,'2' : 2, '3' :3}, {'6' : 6,'5' : 5, '4' : 4}],
[{'1' : 1,'2' : 2, '3' :3}, {'7' : 7,'8' : 8, '9' : 9}]]
結果應為[{'1' : 1,'2' : 2, '3' :3}]
我嘗試使用set intersection,但是python中的字典是不可用的。
怎么解決這個?
列表理解可以在這里工作:
>>> [x for x in dict_list[0] if x in dict_list[1]]
[{'1': 1, '2': 2, '3': 3}]
但這不是一個非常通用的解決方案,因為它假設只存在兩個嵌套列表。
更通用的解決方案是使用collections.Counter()
計算出現的次數,並使用hashable / immutable類型(如frozenset()
或tuple()
存儲字典items()
tuple()
。 然后,所有你需要做的就是篩選數大於 1的出現次數。
例:
>>> from itertools import chain
>>> from collections import Counter
>>> [dict(k) for k, v in Counter(frozenset(x.items()) for x in chain.from_iterable(dict_list)).items() if v > 1]
[{'1': 1, '2': 2, '3': 3}]
這與@Chris_Rands在評論中發布的方法非常相似。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.