Python procedure to populate dictionary from data in 2 separate lists

Go To


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.

2012-04-04 01:21
by user1311698
Is this homework? If not, rethink what is happening upstream; having your data structured in parallel lists is not a good idea and doesn't happen naturally. For example, such things arrive naturally in the same line of a data file or same row of a database table or spreadsheet, and you can stuff them into a dict as you read the input - John Machin 2012-04-04 15:36


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.

2012-04-04 01:24
by Blender
Shouldn't that be birth_years[n] = year[index] - DSM 2012-04-04 01:57
Yep, it should. Thanks - Blender 2012-04-04 02:22


birth_years = {}
for i in range(len(name)):
    birth_years[name[i]] = year[i]
2012-04-04 01:32
by Daniel
How very unpythonic - Joel Cornett 2012-04-04 01:38


Try a dictionary comprehension:

birth_years = {nm:year[idx] for idx, nm in enumerate(name)}
2014-04-03 12:23
by Toadeeza


Your lists would be better named names and years. You got off to a good start by trying to do it with a for loop. Most practical data processing problems involve error checking, which is just a tad difficult with one-liners. Example:

birth_years = {}
for i, name in enumerate(names):
    if name in birth_years:
        log_duplicate(i, name, years[i]))
        birth_years[name] = years[i]
2012-04-04 15:28
by John Machin