简体   繁体   English

如何用Python中字典中的键替换列表中的项目

[英]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_dict 中的键替换 my_list 中的项目,例如...

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:然后我们只需将 dict 应用于每个元素:

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.您可以反转 dict 的键值对,然后迭代您的列表以获取相应的键。

>>> 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:您可以使用列表理解来做到这一点,您需要做的是:根据您的列表对 dict.items 进行排序,然后返回键:

>>> 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 .您可以使用函数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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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