[英]Get particular value from dictionary
How to get a particular key from dictionary in python? 如何从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
: 我们打电话给你的字典
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. 如果没有找到这样的键/值,则会引发
StopIterationError
。 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). 如果找不到这样的密钥(或使用其他默认值),则获取
None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.