Home  >  Article  >  Backend Development  >  How to return keys based on values ​​in python dictionary

How to return keys based on values ​​in python dictionary

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-21 14:19:3121480browse

If no modification to the dictionary occurs during the iteration process, the dict-view objects returned by the two functions .keys() and .values ​​will always maintain a corresponding relationship. The following is an introduction to how python dictionaries return keys based on values.

How to return keys based on values ​​in python dictionary

>>> dicxx = {'a':'001', 'b':'002'}
>>> list(dicxx.keys())[list(dicxx.values()).index("001")]
'a'
>>>

The value in the dictionary does not guarantee uniqueness, so what is found based on the value is a list. However, the key value in the dictionary is unique, so the only value can be found based on the key.

Example:

#根据值查询对应的键
key_list=[]
value_list=[]
mydisc = {'key1':'123','key2':'234','key3':'345'}
for key,value in mydisc.items():
    key_list.append(key)
    value_list.append(value)
get_value = raw_input("请输入要查值:")
if get_value in value_list:
    get_value_index = value_list.index(get_value)
    print "你要查询的值对应的键为:%s" %key_list[get_value_index]
else:
    print "你要查询的值%s不存在" %get_value

Related recommendations: "python video tutorial"

Display results:

The above is the detailed content of How to return keys based on values ​​in python dictionary. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn