Counting values ​​in a dictionary

I have a dictionary as follows.

dictA = { 'a' : ('duck','duck','goose'), 'b' : ('goose','goose'), 'c' : ('duck','duck','duck'), 'd' : ('goose'), 'e' : ('duck','duck') } 

I hope to scroll through dictA and display a list that will show me the keys in dictA that have more than one "duck" in value.

For example, for dictA, this function will display the list below.

 list = ['a', 'c', 'e'] 

I'm sure there is an easy way to do this, but I'm new to Python, and it puzzled me.

+4
source share
3 answers
 [k for (k, v) in dictA.iteritems() if v.count('duck') > 1] 
+13
source

I think this is a good way for beginners. Do not name your list - there is a built-in call to list

 >>> dictA = { ... 'a' : ('duck','duck','goose'), ... 'b' : ('goose','goose'), ... 'c' : ('duck','duck','duck'), ... 'd' : ('goose'), ... 'e' : ('duck','duck') ... } >>> my_list = [] >>> for key in dictA: ... if dictA[key].count('duck') > 1: ... my_list.append(key) ... >>> my_list ['a', 'c', 'e'] 

The next step is to use .items() , so you don't need to look up the value for each key

 >>> my_list = [] >>> for key, value in dictA.items(): ... if value.count('duck') > 1: ... my_list.append(key) ... >>> my_list ['a', 'c', 'e'] 

When you understand this, you will realize that understanding the list in Ignacio is easier to understand.

+4
source

Just for this - here's another, different way:

 >>> from collections import Counter >>> [i for i in dictA if Counter(dictA[i])['duck'] > 1] ['a', 'c', 'e'] 

Counter for - you guessed it - counting things.

+3
source

All Articles