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

10,189

Solution 1

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

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

Solution 2

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 
Share:
10,189
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

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

    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

  • Sven Marnach
    Sven Marnach about 13 years
    If I read the original post correctly, people is a collection of dictionaries, but not a dictionary itself.