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.
>>> 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!