开发者

Python: efficient counting number of unique values of a key in a list of dictionaries

开发者 https://www.devze.com 2023-03-07 06:05 出处:网络
There must be a better way of writing this Python code where I have a list of people (people are dictionaries) and I am trying to find the number of unique values of a certain key (in this case the ke

There must be a better way of writing this Python code where I have a list of people (people are dictionaries) and I am trying to find the number of unique values of a certain key (in this case the key is called Nationality and I am trying to find the number of unique nationalities in the list of people):

开发者_C百科no_of_nationalities = []
for p in people:
    no_of_nationalities.append(p['Nationality'])
print 'There are', len(set(no_of_nationalities)), 'nationalities in this list.'

Many thanks


A better way is to build the set directly from the dictionaries:

print len(set(p['Nationality'] for p in people))


There is collections module

import collections
....
count = collections.Counter()
for p in people:
    count[p['Nationality']] += 1;
print 'There are', len(count), 'nationalities in this list.'

This way you can count each nationality too.

print(count.most_common(16))#print 16 most frequent nationalities 


len(set(x['Nationality'] for x in p))


count = len(set(p['Nationality'] for p in people))
print 'There are' + str(count) + 'nationalities in this list.'
0

精彩评论

暂无评论...
验证码 换一张
取 消