将数组索引映射到字典

时间:2018-12-14 22:16:03

标签: python python-3.x dictionary arraylist

我有一个像这样的数组:

[[12, 14, 74, 55, 78 ]]

还有字典,如:

{'apple': 0, 'banana': 4, 'ice': 3, 'orange': 2, 'cheese': 1 } 

字典键的值是数组的索引,我希望在Python 3中获得此结果:

apple=12
banana=78
ice=55
orange=74
cheese=14

3 个答案:

答案 0 :(得分:0)

这是您要找的吗?

first = [[12, 14, 74, 55, 78 ]]

second = {'apple': 0, 'banana': 4, 'ice': 3, 'orange': 2, 'cheese': 1 } 

result = {key: first[0][val] for key, val in second.items()}
# {'apple': 12, 'banana': 78, 'ice': 55, 'orange': 74, 'cheese': 14}

答案 1 :(得分:0)

那么,这样的事情吗?

>>> l = [[12, 14, 74, 55, 78 ]]
>>> d = {'apple': 0, 'banana': 4, 'ice': 3, 'orange': 2, 'cheese': 1 }
>>> out = {}
>>> for k, v in d.items():
...    out[k] = l[0][v]
...    
>>> out
{'apple': 12, 'banana': 78, 'ice': 55, 'orange': 74, 'cheese': 14}

答案 2 :(得分:0)

您可以遍历字典并打印所有键以及数组中的相应值:

somedict = {'apple': 0, 'banana': 4, 'ice': 3, 'orange': 2, 'cheese': 1 }
somearray = [12, 14, 74, 55, 78]
for k, v in somedict.items():
    print(k + '=' + str(somearray[v]))
相关问题