Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python procedure to populate dictionary from data in 2 separate lists

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.

like image 622
user1311698 Avatar asked Apr 04 '12 01:04

user1311698


1 Answers

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.

like image 56
Blender Avatar answered Sep 28 '22 04:09

Blender