嵌套dict python中唯一值的计数

时间:2016-09-06 16:08:29

标签: python dictionary iterator set

我有一个像这样的词典:

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

我正试图弄清楚每个独特国家和价值的发生次数。

例如,{"Chad": 2, "South Africa": 2,..}{"3000000": 2, "13000": 1,..}

我使用下面的代码可以工作但不是很聪明,有没有更好的方法来做这个没有很长的迭代周期,因为实际的字典很大?

seencountries = {}
seenvalues = {}

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

print seencountries

print seenvalues

1 个答案:

答案 0 :(得分:4)

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