简体   繁体   中英

How to replace items in list with a keys from dictionary in Python

I have a dictionary

my_dict = {"a":1, "b":2, "c":3}

And list

my_list = [2,3,1]

I want to replace items in my_list with keys from my_dict, something like...

my_list = [b, c, a]

How can i achieve this?

I'm sure it's possible to manufacture a list comprehension but this could be one approach (which only ever iterates over the list once and allows you to cover potential edge cases inside the loop):

for key, value in my_dict.items():
    if value not in my_list:
        # Does this case need special handling?
        continue

    index = my_list.index(value)
    my_list[index] = key

There are a few edge cases to consider here, eg what happens if not all items match, what if the dictionary and list are of unequal lengths etc. Depending on your use case you want to make sure to cover all possible edge cases accordingly.

Applied to your example code, it yields the following output:

>>> my_dict = {"a":1, "b":2, "c":3}
>>> my_list = [2,3,1]
>>> my_dict
{'a': 1, 'b': 2, 'c': 3}
>>> my_list
[2, 3, 1]
>>> for key, value in my_dict.items():
...     if value not in my_list:
...         # Does this case need special handling?
...         continue
...     index = my_list.index(value)
...     my_list[index] = key
>>> my_list
['b', 'c', 'a']

Dictionaries are mappings. You want to use reverse mappings (use values to find keys), so let's reverse the dict.

my_dict = {"a":1, "b":2, "c":3}
reversed_dict = {my_dict[k]:k for k in my_dict}

Then we just apply the dict to each element:

my_list = [2,3,1]
result = [reversed_dict[elem] for elem in my_list]

You can reverse the key value pair of your dict and then iterate your list to get the corresponding keys.

>>> rev_dict = dict((v,k) for k,v in my_dict.items())
>>> rev_dict
{1: 'a', 2: 'b', 3: 'c'}
>>> [rev_dict[x] for x in my_list]
['b', 'c', 'a']

You can do this with list comprehension, what you need to do is: sort the dict.items according to your list, then return the key:

>>> my_dict = {"a":1, "b":2, "c":3}
>>> my_list = [2,3,1]
>>> [key for key, value in sorted(my_dict.items(), key = lambda x:my_list.index(x[1]))]
['b', 'c', 'a']
rev = { v:k for k,v in my_dict.items()}
new_list = [rev[item] for item in my_list]

Output new_list:

['b', 'c', 'a']

This will probably work

for key, val in my_dict.items():
    for i, v in enumerate(my_list):
        if v == val:
            my_list[i] = key

You can use the function itemgetter . First, you need to swap keys and values in your dictionary:

from operator import itemgetter

dct = {"a": 1, "b": 2, "c": 3}
lst = [2, 3, 1]

dct = {v: k for k, v in dct.items()}
# {1: 'a', 2: 'b', 3: 'c'}

print(list(itemgetter(*lst)(dct)))
# ['b', 'c', 'a']

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