John Lee
John Lee

Reputation: 45

Mapping lists to individual dictionary keys and values

I have 5 lists. I would like to map these 5 lists to a list of dictionaries, each one with a key/value pair from each of the 5 lists for every dictionary instance [n]. My first thought is to set up a loop to enumerate each occurrence of a dictionary in the list of dictionaries, but not sure what that might look like. Any thoughts?

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"]

list of dictionaries such that

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

Upvotes: 0

Views: 31

Answers (2)

doctorlove
doctorlove

Reputation: 19232

The zip function will allow you to "pair" up or tuple up several lists.

For the first three attributes, you can do this to get a tuple:

>>> 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')

If you make a list

L = []

you can add dictionaries to it:

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

That's for the first three - extending to the whole lot should be clear.

Upvotes: 0

user8408080
user8408080

Reputation: 2468

You can use the built-in function zip and list/dict comprehensions for this:

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]

Upvotes: 1

Related Questions