gokyori
gokyori

Reputation: 367

How to count number of times a value appears in nested dictionary in python?

I have a dictionary of dictionary for example:

d={'object1':{'time1':['value1','value2'],'time2':['value1','value4']},

'object2':{'time1':['value1','value6'],'time2':['value7','value8']}}

How can I iterate over the dictionary such that I can find value1 appears 3 times in total?

Upvotes: 1

Views: 4909

Answers (5)

Tiny.D
Tiny.D

Reputation: 6556

Try with list.count(x):

d={'object1':{'time1':['value1','value1','value2'],'time2':['value1','value4']},'object2':{'time1':['value1','value6'],'time2':['value7','value8']}}
cnt =[item for l in [v2 for v1 in d.values() for v2 in v1.values()] for item in l].count('value1')
print(cnt) # print 4

Upvotes: 2

atru
atru

Reputation: 4744

This may not be the most elegant solution but it works for your nested dictionary problem:

lst = d.values()
sub_val = [temp.values() for temp in lst]
d_val = [item for sublist in sub_val for item in sublist]
d_val = [item for sublist in d_val for item in sublist]
count = d_val.count('value1')

lst is a list of nested dictionaries. sub_val creates a nested list of values for each nested dictionary. This results in a list of double nested list hence d_val flattening appears twice. Finally, count returns number of occurrences of value1 in the flattened list d_val.

Upvotes: 1

Roee N
Roee N

Reputation: 502

Well the tricky way is:

print(str(d).count('value1'))

but you can always just do a nested loop.

Upvotes: 2

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48047

You may use the combination of collections.Counter and itertools.chain to achieve this as:

>>> from itertools import chain
>>> from collections import Counter

>>> d={'time1':['value1','value2'],'time2':['value1','value4'],'time3':['value1','value5']}

>>> counter_dict = Counter(chain(*d.values()))
#    ^ dict holding the count of each value

In order to fetch the count of 'value1' in your counter_dict, you need to just access the value of this key as:

>>> counter_dict['value1']
3

Upvotes: 2

Deepansh Sachdeva
Deepansh Sachdeva

Reputation: 1198

You can iterate over the values & count like this:

n = 0

for list_data in d.values():
    if 'value1' in list_data:
        n = n + 1

print(n)

Upvotes: 3

Related Questions