I am trying to create an automated python procedure that uses two separate lists to create a dictionary and so far I am failing. I have two sorted lists where the nth item in the fist list corresponds to the nth item in the second list and I want to combine them into a dictionary.
For example, a subset of the 2 lists are as follows;
name = ['Adam', 'Alfred', 'Amy', 'Andy', 'Bob']
year = [1972, 1968, 1985, 1991, 1989]
I would want my output to be:
birth_years = {'Adam':1972, 'Alfred':1968, 'Amy':1985, 'Andy':1991, 'Bob':1989}
I was trying to do this with a for loop, but I could not get it to work. I appreciate any help.
Use the zip
and dict
functions to construct a dictionary out of a list of tuples:
birth_years = dict(zip(name, year))
And if you're curious, this would be how I would try to do it with a for
loop:
birth_years = {}
for index, n in enumerate(name):
birth_years[n] = years[index]
I think I like the first example more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With