简体   繁体   中英

Iterating over all the values and finding the key for the value

I need iterate over the dictionary and find keys of certain values. The dictionary is as follows:

z1 = {9376: 172, 1: 168, 2: 179, 3: 2, 132: 9740, 145: 179, 137: 185, 135: 1, 142: 13528, 113: 158, 9781: 176, 9782: 168, 152: 13527, 9375: 9504, 127: 1}

also I am having a list which I want to check over the dictionary and find out the corresponding keys.

z =[13527,9741,9740,9505,9504,200,189,185,176,172,168,1]

I need to find which values from z are present in z1 and then make the dictionary of the matched value and the key. Following is the code I am using

for i in range(len(z1)) :
    try :
        p = z[i]
        a = list(z1.keys())[list(z1.values()).index(p)]
        e1.append(a)
        e2.append(p)
    except (ValueError, IndexError,AttributeError) :
        continue
e3 = list(zip(e1,e2))
print(e3)

The result I am getting is

[(152, 13527), (132, 9740), (9375, 9504), (137, 185), (9781, 176), (9376, 172), (1, 168), (135, 1)]

Now in the dictionary z1, you can see that value 168,1 is repeated twice and having unique keys. When I am running the for loop, I am just getting single key-value pair. What should I do to get all the keys having same values. ie my final answer should like

[(152, 13527), (132, 9740), (9375, 9504), (137, 185), (9781, 176), (9376, 172), (1, 168), (9782,168) (135, 1), (127,1)]

Maybe this is what you need:

e3 = [(k, i) for i in z for k in z1 if i==z1[k]]

Gives me:

[(152, 13527), (132, 9740), (9375, 9504), (137, 185), (9781, 176), (9376, 172), (1, 168), (9782, 168), (135, 1), (127, 1)]

Traversing on the values of a dictionary defeats the purpose of using the dictionary in the first place.

If you need to store the key, value because you are using it somewhere, then I also suggest to build a reverse dictionary of value, key .

If the values are not unique, build a dictionary like value, [list_of_keys] . This approach would be much faster.

Traversing on the values would be O(n) every time, but building a reverse dictionary would be O(1) . For larger values of n , your program will run significantly faster.

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