我们说有3个字典first
,second
,third
,其值如下
first = {'a': 0.2, 'b': 0.001}
second = {'a': 0.99, 'c': 0.78}
third = {'c': 1, 'd': 0.1}
total = {'_first': first, '_second': second, '_third':third}
有没有一种方法可以快速获取可以保存每个键的计数信息的数据结构(a
,b
,c
, d
)使用 total
而不是多个词典。例如,由于在这些词典中{'a':2, 'b':2, 'c':2, 'd':1}
,a
,b
键两次出现,而c
只出现一次,因此答案应返回类似d
的内容。
答案 0 :(得分:2)
from collections import Counter
from itertools import chain
first = {'a': 0.2, 'b': 0.001}
second = {'a': 0.99, 'c': 0.78}
third = {'c': 1, 'd': 0.1}
print(Counter(chain(first, second, third)))
使用存储在字典total
中的变化数量的字典来说明已编辑的问题
total = {'_first': first, '_second': second, '_third':third}
print(Counter(chain.from_iterable(total.values())))
答案 1 :(得分:1)
没有任何进口:
def dict_keys_count(*dicts):
keys = []
for _dict in dicts:
keys += _dict.keys()
keys_counts = {}
for key in set(keys):
keys_counts[key] = keys.count(key)
return keys_counts
print(dict_keys_count(first,second,third))
# {'b': 1, 'c': 2, 'd': 1, 'a': 2}
速度比较:我与接受的答案
from time import time
t0 = time()
for _ in range(int(1e7)):
dict_keys_count(first,second,third)
print("No-import solution {}:".format(time() - t0))
# 17.77
t0 = time()
for _ in range(int(1e7)):
Counter(chain(first, second, third))
print("Accepted solution {}:".format(time() - t0))
# 24.01
答案 2 :(得分:0)
您可以使用collections.Counter
:
import collections
first = {'a': 0.2, 'b': 0.001}
second = {'a': 0.99, 'c': 0.78}
third = {'c': 1, 'd': 0.1}
r = dict(collections.Counter([*first, *second, *third]))
输出:
{'a': 2, 'c': 2, 'b': 1, 'd': 1}