Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting values in 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'm hoping to loop through dictA and output a list that will show me the keys in dictA that have more than one "duck" in value.

For example, for dictA this function would output the below list.

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

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

like image 371
cloud36 Avatar asked Dec 01 '22 04:12

cloud36


2 Answers

[k for (k, v) in dictA.iteritems() if v.count('duck') > 1]
like image 156
Ignacio Vazquez-Abrams Avatar answered Dec 04 '22 09:12

Ignacio Vazquez-Abrams


I think this is a good way for beginners. Don't call your list list - there is a builtin called 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']

Next stage is to use .items() so you don't need to look the value up 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 that, you'll find the list comprehension in Ignacio's answer easier to understand.

like image 36
John La Rooy Avatar answered Dec 04 '22 10:12

John La Rooy