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

爱喝马黛茶的安东尼
Release: 2019-06-21 14:19:31
Original
21535 people have browsed it

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'
>>>
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template