用Python方式计算多个dict的键

时间:2019-10-03 16:10:45

标签: python counter

我们说有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}

有没有一种方法可以快速获取可以保存每个键的计数信息的数据结构(abcd)使用 total 而不是多个词典。例如,由于在这些词典中{'a':2, 'b':2, 'c':2, 'd':1}ab键两次出现,而c只出现一次,因此答案应返回类似d的内容。

3 个答案:

答案 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}