如何通过调节字典来创建列表?

时间:2019-09-20 08:56:37

标签: python python-3.x list dictionary

具有这样的字典

d = {
        'airplane': 0, 
        'automobile': 1, 
        'bird': 2, 
        'cat': 3, 
        'deer': 4, 
        'dog': 5, 
        'frog': 6, 
        'horse': 7, 
        'ship': 8, 
        'truck': 9
}

和一个列表

l = [3, 4, 1, 7, 9, 0]

我如何创建字典的新列表条件

new_list = ['cat', 'deer', 'automobile', 'horse', 'truck', 'airplane']

5 个答案:

答案 0 :(得分:0)

那呢?

d = {'airplane': 0, 'automobile': 1, 'bird': 2, 'cat': 3, 'deer': 4, 'dog': 5, 'frog': 6, 'horse': 7, 'ship': 8, 'truck': 9}
l = [3, 4, 1, 7, 9, 0]
reversed_d = {v: k for k, v in d.items()}
new_list = [reversed_d[i] for i in l]
print(new_list)
# ['cat', 'deer', 'automobile', 'horse', 'truck', 'airplane']

请注意,通常,生成reversed_d不能很好地与重复项配合使用。

答案 1 :(得分:0)

from collections import OrderedDict
d1 = OrderedDict(d)
d1_keys, d1_values = list(d1.keys()), list(d1.values())
new_list = [d1_keys[d1_values.index(i)] for i in l]

答案 2 :(得分:0)

您只需要从字典“ d”中获取具有与列表“ l”中存在的数字相对应的值的键即可。您可以使用列表推导功能轻松做到这一点。

print([list(d.keys())[list(d.values()).index(num)] for num in l])

由于您使用的是python-3,因此d.keys()和d.values()不会返回列表;所以您需要自己做,因此它们是使用list()进行类型转换的。

输出

['cat', 'deer', 'automobile', 'horse', 'truck', 'airplane']

答案 3 :(得分:-1)

首先,示例中的字典MOI ANNEE --- ---------- sep 19 oct 19 nov 19 dec 19 jan 20 fev 20 mar 20 并不是理想的查找结构,因为字典是用其键而不是值来索引的。此外,不能保证值在所有键中都是唯一的。

如果您确定值是唯一的,则可以在以下位置更改字典:

d

之后,获得第二个列表只是另一个列表理解:

d = {'airplane': 0, 'automobile': 1, 'bird': 2, 'cat': 3, 'deer': 4, 'dog': 5, 'frog': 6, 'horse': 7, 'ship': 8, 'truck': 9}
di = {value: key for key, value in d.items()}

答案 4 :(得分:-1)

只需尝试如下操作:

d = {'airplane': 0, 'automobile': 1, 'bird': 2, 'cat': 3, 'deer': 4, 'dog': 5, 'frog': 6, 'horse': 7, 'ship': 8, 'truck': 9}
l = [3, 4, 1, 7, 9, 0]

new_list = [list(d)[i] for i in l]