简体   繁体   中英

Accessing the key of a dictionary with a list of values

Here are the main lists and dictionary that I am trying to work on:

Nodes = [[0,0,0],[1,1,1],[2,2,2]]
Lengths= [50,60,70]
dic= {'A':[Nodes[0],Lengths[0]],'B':[Nodes[1],Lengths[1]],'C':[Nodes[2],Lengths[2]]}

In this example, I am trying to get the key of the dictionary if one item in the values exists. For example, I am expecting to get the key 'A' if I have 50 in the list of values since it is represented as Lengths[0]. so far, I have been working with a function that returns the key if I provided the whole list of values, as follows.

def get_key(Val): 
    for key, value in a.items(): 
         if Val == value: 
            return key 

print(get_key([Nodes[0],Lengths[0]])) 

Help would be appreciated. Many Thanks in advance.

You can achieve this by populating a lookup dictionary from the keys and Lengths in your dic dictionary.

Nodes = [[0,0,0],[1,1,1],[2,2,2]]
Lengths= [50,60,70]
dic= {'A':[Nodes[0],Lengths[0]],'B':[Nodes[1],Lengths[1]],'C':[Nodes[2],Lengths[2]]}

keyByLength = {v[1]: k for k, v in dic.items()}

print(keyByLength[50])
print(keyByLength[60])
print(keyByLength[70])

Outputs

A
B
C

I think your implementation is almost there, you just need to change the lookup to something like this:

def get_key(Val): 
    for key, value in dic.items(): 
         if Val in value: 
            return key 

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