简体   繁体   English

如何根据键从字典中检索值?

[英]How to retrieve value from a dictionary based on key?

I am stuck at this minor problem for quite some time and cannot understand why.我被这个小问题困住了很长一段时间,不明白为什么。

Let's say I have a list :假设我有一个列表:

test = ['1', '2', '3']

I convert this into dictionary using我将其转换为字典使用

test_dict =  { i : test[i] for i in range(0, len(test))}

{0: '1', 1: '2', 2: '3'}

Now when I access key based on value like this现在,当我根据这样的值访问密钥时

print (a.get('1')) 

it gives me None.它给了我无。 Any suggestions in this regard would be helpful.在这方面的任何建议都会有所帮助。

Its a problem of type它的类型问题

test_dict =  { i : test[i] for i in range(0, len(test))}

{0: '1', 1: '2', 2: '3'}

The keys will be of integer type and not string type.键将是整数类型而不是字符串类型。

Try this out instead试试这个

print (a.get(1))

Edit: To get the keys, you can flip the dictionary creation编辑:要获取密钥,您可以翻转字典创建

test_dict =  { test[i] : i for i in range(0, len(test))}

print (a.get(1))
0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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