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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With