我有一个包含键的列表,我希望在键值出现时从字典中获取键值。暂时我有一个函数,它接受一个带有键的列表,但它只返回同一个键出现的一次,尽管同一个键在列表中出现了很多次。
例如 [1,2,3]
而不是 [1,2,2,2,1,1,3,3]
这是我的代码:
key_list = [1,2,2,2,1,1,3,3]
dict_ = {1:'a', 2:b, 3:'c'}
# current function that only returns one occurence per key in the list with keys, key_list`
def get_values_from_dict(dict_, key_list):
return [v for k, v in dict_.items() if k in key_list]
这是我的预期输出:
['a', 'b', 'b', 'b', 'a', 'a', 'c', 'c']
最佳答案
你的列表理解应该用 key_list
中的每个值索引 dict_
:
>>> key_list = [1,2,2,2,1,1,3,3]
>>> dict_ = {1:'a', 2:'b', 3:'c'}
>>> def get_values_from_dict(dict_, key_list):
... return [dict_[x] for x in key_list]
...
>>> get_values_from_dict(dict_, key_list)
['a', 'b', 'b', 'b', 'a', 'a', 'c', 'c']
>>>
您当前的代码不正确,因为它在做一些不同的事情:它正在获取 dict_
中所有具有 key_list
中键的值。换句话说,它通过 key_list
过滤值。
关于python - 从键列表中获取字典中的所有值,其中相同的键多次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27138747/