Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 230
Antony Avatar asked May 19 '11 17:05

Antony


2 Answers

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

print len(set(p['Nationality'] for p in people))
like image 151
Sven Marnach Avatar answered Oct 04 '22 03:10

Sven Marnach


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 
like image 45
Nikiton Avatar answered Oct 04 '22 04:10

Nikiton