计算多个字典键的 Pythonic 方法

Pythonic way to count keys of multiple dicts

假设有 3 个字典 firstsecondthird 具有以下值

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 而不是多个词典。例如,答案应该是 return 类似 {'a':2, 'b':2, 'c':2, 'd':1} 的东西,因为 abc 键出现了两次,而 d 只出现了一次字典。

您可以使用 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}
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())))

没有任何导入:

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