如何在 python 中从字典中获取特定的键?
我有一本字典:
dict = {'redorange':'1', 'blackhawak':'2', 'garlicbread':'3'}
我想获取键名中包含大蒜的那个键的值。
我怎样才能实现它?
最佳答案
让我们称你的字典为d
:
print [v for k,v in d.iteritems() if 'garlic' in k]
打印所有对应值的列表:
['3']
如果你知道你想要一个单一的值:
print next(v for k,v in d.iteritems() if 'garlic' in k)
打印
'3'
如果没有找到这样的键/值,这会引发 StopIterationError
。添加默认值:
print next((v for k,v in d.iteritems() if 'garlic' in k), None)
如果找不到这样的键(或使用其他默认值),则获取 None
。
关于python - 从字典中获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14830128/