Can I Use A List Comprehension On A List Of Dictionaries If A Key Is Missing?
I want to count the number of times specific values appear in a list of dictionaries. However, I know that some of these dictionaries will not have the key. I do not know which tho
Solution 1:
You can explicitly check if key2
is in a dictionary:
Counter(r['key2'] for r in list_of_dicts if 'key2' in r)
Solution 2:
get
lets you specify a default value to return if the key isn't present. thus:
In [186]: Counter(r.get('key2',None) for r in list_of_dicts)
Out[186]: Counter({'testing': 3, None: 3})
Where the None
entry tells us how many dictionaries were missing this value. It might be nice to know that. If you don't care, it probably doesn't matter much whether you use this or the if
clause.
Post a Comment for "Can I Use A List Comprehension On A List Of Dictionaries If A Key Is Missing?"