简体   繁体   中英

Get particular value from dictionary

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM