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.
[k for (k, v) in dictA.iteritems() if v.count('duck') > 1]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With