cloud36
cloud36

Reputation: 1066

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.

Upvotes: 4

Views: 24405

Answers (3)

Burhan Khalid
Burhan Khalid

Reputation: 174614

Just for the heck of it - here is the other, other way:

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

Counter is for - you guessed it - counting things.

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304117

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.

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

[k for (k, v) in dictA.iteritems() if v.count('duck') > 1]

Upvotes: 13

Related Questions