Dhruv Ghulati Dhruv Ghulati - 1 year ago 65
Python Question

Count of unique values in nested dict python

I have a dict like:

dict = {
"a": {"Azerbaijan": 20006.0, "Germany": 20016.571428571428},
"b": {"Chad": 13000.0, "South Africa": 3000000.0},
"c": {"Chad": 200061.0, "South Africa": 3000000.0}

And I am trying to get a dict of the counts of the occurrences of each unique country and value.

For example,
{"Chad": 2, "South Africa": 2,..}
{"3000000": 2, "13000": 1,..}

I am using the code below which works but is not very smart, is there a better way to do this without a long iteration cycle, since the actual dict is massive?

seencountries = {}
seenvalues = {}

for key, innerdict in dict.iteritems():
for country, value in innerdict.iteritems():
if value not in seenvalues.keys():
seenvalues[value] = 0
if country not in seencountries.keys():
seencountries[country] = 0

print seencountries

print seenvalues

Answer Source
from collections import Counter
seen_countries = Counter()
seen_values = Counter()
for data in your_dicts.itervalues():
    seen_countries += Counter(data.keys())
    seen_values += Counter(data.values())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download