RTM
RTM

Reputation: 789

Pythonic way to count keys of multiple dicts

Lets say there are 3 dictionaries first, second, third with following values

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}

Is there a way to quickly get a data structure which can hold the information of the count of each key (a, b, c, d) using total instead of multiple dictionaries. For example, the answer should return something like {'a':2, 'b':2, 'c':2, 'd':1} since a, b, c key occurred twice while d occurred only once in these dictionaries.

Upvotes: 1

Views: 1526

Answers (3)

OverLordGoldDragon
OverLordGoldDragon

Reputation: 19836

Without any imports:

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}

Speed comparison: my vs accepted answer

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

Upvotes: 1

buran
buran

Reputation: 14273

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)))

to account for edited question with variable number of dicts stored in a dict total

total = {'_first': first, '_second': second, '_third':third}
print(Counter(chain.from_iterable(total.values())))

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71471

You can use 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]))

Output:

{'a': 2, 'c': 2, 'b': 1, 'd': 1}

Upvotes: 0

Related Questions