Reputation: 19164
How to get a particular key from dictionary in python?
I have a dictionary as :
dict = {'redorange':'1', 'blackhawak':'2', 'garlicbread':'3'}
I want to get value of that key which contains garlic in its key name.
How I can achieve it?
Upvotes: 2
Views: 416
Reputation: 212885
Let's call your dictionary d
:
print [v for k,v in d.iteritems() if 'garlic' in k]
prints a list of all corresponding values:
['3']
If you know you want a single value:
print next(v for k,v in d.iteritems() if 'garlic' in k)
prints
'3'
This raises StopIterationError
if no such key/value is found. Add the default value:
print next((v for k,v in d.iteritems() if 'garlic' in k), None)
to get None
if such a key is not found (or use another default value).
Upvotes: 9