Python: How to map values from list to its related dictionary key

Viewed 64

I have a dictionary dic with this key and value pair: (note: this dic is bijective, i.e: one-to-one mapping)

dic = {
    0: 0, 
    30: 1, 
    35: 2, 
    42: 3, 
    53: 4, 
    54: 5, 
    55: 6, 
    81: 7, 
    83: 8, 
    95: 9, 
    99: 10
}

In my source code, there is list L which is generated from a particular computation. Values in L are actually associated with dic values. So, based on dic, I want this L list:

L = [0, 0, 7, 2, 2, 1, 9]

to be converted to key values from dic. This is the desired output out:

out = [0, 0, 81, 35, 35, 30, 95] 

What kind of list comprehension can I use to achieve the desired output?

2 Answers

You can create the inverted dictionary from the original one and use that to get desired result as:

dic = {0: 0, 
30: 1, 
35: 2, 
42: 3, 
53: 4, 
54: 5, 
55: 6, 
81: 7, 
83: 8, 
95: 9, 
99: 10}

invertedDic = {v:k  for k, v in dic.items()}
L = [0, 0, 7, 2, 2, 1, 9]
res = [invertedDic[elt] for elt in L]
print(res)

Output:

[0, 0, 81, 35, 35, 30, 95]

Also, it is not recommended to use keywords like dict for object names.

There is another solution, which doesn't require to generate an intermediate dictionary with values and keys switched. It just does the same in one step as the solution proposed by @Krishna Chaurasia. Limitations are the same, especially you have to ensure that dic is bijective elsewhere for this to work.

dic = {
    0: 0, 
    30: 1, 
    35: 2, 
    42: 3, 
    53: 4, 
    54: 5, 
    55: 6, 
    81: 7, 
    83: 8, 
    95: 9, 
    99: 10
}

L = [0, 0, 7, 2, 2, 1, 9]

out = [k for el in L for k,v in dic.items() if el==v]

Output

print(out)
# [0, 0, 81, 35, 35, 30, 95]
Related