![](/img/trans.png)
[英]What is the best way to access the last entered key in a default dict in Python?
[英]Python what is the best way to get the key from dict by value
所以让我们假设我有以下字典:
data = {
'A': ['A1', 'A2', 'A3'],
'B': ['B1', 'B2', 'B3'],
}
问题是获取给定值的密钥的最佳方法是什么。 例如,我想在字典中获取一个值包含A2
的键:
def get_key_depending_on_value(value):
for key in data.keys():
if value in data[key]:
return key
return 'There is no such string in data\'s values'
result = get_key_depending_on_value('A2')
print(result) # prints A
我本可以编写这样的 function,但这是最佳实践还是 python 内置了一些东西?
我建议你生成一个新字典:
data = {
'A': ['A1', 'A2', 'A3'],
'B': ['B1', 'B2', 'B3'],
}
d = {}
for key, values in data.items():
d.update({value: key for value in values})
现在您只需执行d[value]
即可获取密钥。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.