Python procedure to populate a 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 element in the first list corresponds to the nth element in the second list, and I want to combine them into a dictionary.

For example, a subset of 2 lists is as follows:

name = ['Adam', 'Alfred', 'Amy', 'Andy', 'Bob']
year = [1972, 1968, 1985, 1991, 1989]

I want my output to be:

birth_years = {'Adam':1972, 'Alfred':1968, 'Amy':1985, 'Andy':1991, 'Bob':1989}

I tried to do this with a for loop, but I could not get it to work. I appreciate any help.

+5
source share
4 answers

Use the functions zipand dictto build a dictionary from the list of tuples:

birth_years = dict(zip(name, year))

, for:

birth_years = {}

for index, n in enumerate(name):
  birth_years[n] = years[index]

, .

+14
birth_years = {}
for i in range(len(name)):
    birth_years[name[i]] = year[i]
+1

:

birth_years = {nm:year[idx] for idx, nm in enumerate(name)}
+1

Your listings will be better named namesand years. You started great by trying to do this with a loop for. Most of the practical data processing problems are error checking, which is a bit more complicated with single-line ones. Example:

birth_years = {}
for i, name in enumerate(names):
    if name in birth_years:
        log_duplicate(i, name, years[i]))
    else:
        birth_years[name] = years[i]
0
source

All Articles