简体   繁体   中英

Fetching dictionary key using list values

I have a dictionary where the value of the dictionary is in list. i know only one value of the list and wanted to fetch the key of that value.example:

mydict={"java":[100,200,300], "python":[500,600]}

print(list(mydict.keys())[list(mydict.values()).index([100])] #gives error as 100 is not the only element in the list 

i know the value 100 and want to get the key of the 100 ie i want to print "java" by just using 100 value. is it possible to get the key just by knowing a single element of the list.

Iterate over the key value pairs of the dictionary, and if your value is in the value (the list), return the key:

def findkey(d, value):
    for k, v in d.items():
        if value in v:
            return k
    return None # optional

>>> findkey(mydict, 100)
'java'

>>> findkey(mydict, 42)
None

This should help you:

a = 100
for key, value in mydict.items():
    if a in value:
        print(key)

Are you going to be doing this a lot with this dictionary? Create a reverse dictionary.

reverse_dictionary = { value: key for key, values in mydict.items() 
                       for value in values}

This will create a dictionary mapping each of the integer values back to its key.

Try this:

from collections import defaultdict


def find_key_by_value(get_dict, get_value):
    values_by_keys_dict = defaultdict(list)
    for key, value in get_dict.items():
        for sub_values in value:
            values_by_keys_dict[sub_values].append(key)

    return values_by_keys_dict[get_value]


dict1 = {"java": [100, 200, 300], "python": [500, 600]}
dict2 = {"java": [100, 200, 300], "python": [500, 600], "c": [500, 700]}
dict3 = {"java": [100, 200, 300], "python": [500, 600], "c": [500, 700, 200], "php": [600, 200, 1000]}

print(find_key_by_value(dict1, 100))
print(find_key_by_value(dict2, 500))
print(find_key_by_value(dict3, 200))

Output:

['java']
['python', 'c']
['java', 'c', 'php']
get_key = lambda d,x : [ k for k,v in d.items() if x in v][0] get_key(mydict, 100) # outputs 'java'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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