Antony
Antony

Reputation: 51

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

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

Upvotes: 5

Views: 10504

Answers (4)

Nikiton
Nikiton

Reputation: 278

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 

Upvotes: 2

phihag
phihag

Reputation: 287875

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

Upvotes: 0

jonesy
jonesy

Reputation: 3542

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

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601729

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

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

Upvotes: 11

Related Questions