将列表映射到单个词典键和值

时间:2019-02-08 13:57:34

标签: python-3.x dictionary

我有5个清单。我想将这5个列表映射到字典列表,每个字典实例中每个字典实例[n]的5个列表中的每个都有一个键/值对。我的第一个想法是建立一个循环,以枚举字典列表中每本字典的出现,但不确定那是什么样。有什么想法吗?

name = ["John", "Sally", "Allen", "Nick", "Charles", "Richie", "Derek"]
age = [21, 36, 33, 29, 40, 18, 35]
hometown = ["New York", "Washington", "Philadelphia", "Atlanta", "Miami", "LA", "Seattle"]
favorite_food = ["chicken", "steak", "spaghetti", "fish", "oreos", "hamburger", "cereal"]
pet = ["cat", "fish", "dog", "hamster", "dog", "cat", "snake"]

这样的词典列表

D[0]={'name':'John', 'age':'21', 'hometown': 'New York', 'favorite_food': 
'chicken', 'pet': 'cat'}

2 个答案:

答案 0 :(得分:1)

您可以使用内置函数zip并为此列出/ dict理解:

name = ["John", "Sally", "Allen", "Nick", "Charles", "Richie", "Derek"]
age = [21, 36, 33, 29, 40, 18, 35]
hometown = ["New York", "Washington", "Philadelphia", "Atlanta", "Miami", "LA", 
"Seattle"]
favorite_food = ["chicken", "steak", "spaghetti", "fish", "oreos", "hamburger", "cereal"]
pet = ["cat", "fish", "dog", "hamster", "dog", "cat", "snake"]

fields = ["name", "age", "hometown", "favourite_food", "pet"]

zipped = zip(name, age, hometown, favorite_food, pet)

d = [{k: v for k, v in zip(fields,el)} for el in zipped]

答案 1 :(得分:0)

通过zip函数,您可以“配对”或元组几个列表。

对于前三个属性,您可以执行以下操作以获取元组:

>>> for i in zip(name, age, hometown):
...   print(i)
...
('John', 21, 'New York')
('Sally', 36, 'Washington')
('Allen', 33, 'Philadelphia')
('Nick', 29, 'Atlanta')
('Charles', 40, 'Miami')
('Richie', 18, 'LA')
('Derek', 35, 'Seattle')

如果您列出列表

L = []

您可以向其添加字典:

>>> L=[]
>>> for i in zip(name, age, hometown):
...   d = {}
...   d['name']=t[0]
...   d['age']=t[1]
...   d['hometown']=t[2]
...   L.append(d)
...

这是针对前三个的-应该很清楚地扩展到整个批次。