Bjorn Bjorn - 1 month ago 7
Python Question

Python 2.7.12: How to combine two lists into a dictionary

I've searched google and the documentation, but I'm not able to find the answer for a (I guess) simple question. I have to corresponding lists.

NAMES = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank',
'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']

AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]


These lists must become a dictionary where AGES is the key. I've written a function, however it overwrites the previous inserted value in the key..

def combine_lists(list_a, list_b):
dictionary = dict()
for i in range(len(list_a)):
dictionary[list_a[i]] = list_b[i]
return dictionary

print combine_lists(AGES, NAMES)


Executing the program gives me this:

{18: 'Dan', 19: 'Larry', 20: 'Gary', 21: 'Bob', 22: 'Kelly'}


What is the correct way to tackle this (simple) problem?

UPDATE:

What I want is that there are multiple values linked to a key, so that the key 18 gives me not only Dan, but Cathy as well.

Answer

If you want the entries to be lists...

from collections import defaultdict

age_name_dict = defaultdict(list)
for name, age in zip(NAMES, AGE):
    age_name_dict[age].append(name)