Python:如果在另一个列表中找到值,如何将dict中的值附加到列表中

时间:2012-01-29 17:19:55

标签: python list dictionary

示例:

list1 =['a','b','c','d']
new_list = []
dict = {'a':24, 'b':53 ,'c':26, 'd':9}

我如何获取list1并将dict的关联值附加到new_list中,以便生成:

new_list = [24,53,26,9]

5 个答案:

答案 0 :(得分:10)

不要使用'dict'作为变量名,它会影响内置的dict()函数。

list1 =['a','b','c','d']
d = {'a':24, 'b':53 ,'c':26, 'd':9}
new_list = [d[k] for k in list1]
assert new_list == [24, 53, 26, 9]

答案 1 :(得分:3)

假设list1中的所有元素都是dict中的键,这是我能想到的最简单的解决方案:

list1 =['a','b','c','d']
new_list = []
dict = {'a':24, 'b':53 ,'c':26, 'd':9}

for it in list1:
    new_list.append(dict[it])

答案 2 :(得分:2)

list1 =['a','b','c','d']
d = {'a':24, 'b':53 ,'c':26, 'd':9}
new_list = map(lambda x: d[x], list1)

或者如果你真的需要追加而不是替换:

new_list.extend(map(lambda x: d[x], list1))

答案 3 :(得分:1)

这个怎么样?

for key in list1:
    new_list.append(dict[key])

print list1

示例输出:

[24, 53, 26, 9]

答案 4 :(得分:1)

试试这个:

lst = ['a','b','c','d']
dct = {'a':24, 'b':53 ,'c':26, 'd':9}
new_list = [dct[k] for k in lst]