Nina Nina - 1 year ago 61
Python Question

Python dictionary: number of keys with specific number of values

I have a huge dictionary that looks like this:

data = {'this': [{'DT': 100}], 'run': [{'NN': 215}, {'VB': 2}], 'the': [{'NNP': 6}, {'JJ': 7}, {'DT': 39517}]}

What I would like to to do is to run enquires that would return ,for example, the number of keys with exactly two values, in which case the answer is one because
is the only one with exactly two values
{'NN': 215}
{'VB': 2}

I think this could be done with regular expression but could not find out how.

Answer Source

This will do the job:

print len( filter( lambda x: len( x ) == 2, data.values() ) )

The lambda returns true when the length of an item is 2. filter() selects only those items where the lambda returns true, and then we count the length of the sequence returned by filter(). data.values() allows us to filter on the values from the dict rather than the keys (which is what plain data would've given us). Since you only wanted the count, the values are all that's needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download