user1919
user1919

Reputation: 3938

How to map multiple lists to one dictionary?

I used this code:

dictionary = dict(zip(list1, list2))

in order to map two lists in a dictionary. Where:

list1 = ('a','b','c')
list2 = ('1','2','3')

The dictionary equals to:

{'a': 1, 'c': 3, 'b': 2}

Is there a way to add a third list:

list3 = ('4','5','6')

so that the dictionary will equal to:

{'a': [1,4], 'c': [3,5], 'b': [2,6]}

This third list has to be added so that it follows the existing mapping.

The idea is to make this work iteratively in a for loop and several dozens of values to the correctly mapped keyword. Is something like this possible?

Upvotes: 13

Views: 40099

Answers (2)

mgilson
mgilson

Reputation: 310287

dict((z[0], list(z[1:])) for z in zip(list1, list2, list3))

will work. Or, if you prefer the slightly nicer dictionary comprehension syntax:

{z[0]: list(z[1:]) for z in zip(list1, list2, list3)}

This scales up to to an arbitrary number of lists easily:

list_of_lists = [list1, list2, list3, ...]
{z[0]: list(z[1:]) for z in zip(*list_of_lists)} 

And if you want to convert the type to make sure that the value lists contain all integers:

def to_int(iterable):
    return [int(x) for x in iterable]

{z[0]: to_int(z[1:]) for z in zip(*list_of_lists)}

Of course, you could do that in one line, but I'd rather not.

Upvotes: 19

unutbu
unutbu

Reputation: 880927

In [12]: list1 = ('a','b','c')

In [13]: list2 = ('1','2','3')

In [14]: list3 = ('4','5','6')

In [15]: zip(list2, list3)
Out[15]: [('1', '4'), ('2', '5'), ('3', '6')]

In [16]: dict(zip(list1, zip(list2, list3)))
Out[16]: {'a': ('1', '4'), 'b': ('2', '5'), 'c': ('3', '6')}

In [17]: dict(zip(list1, zip(map(int, list2), map(int, list3))))
Out[17]: {'a': (1, 4), 'b': (2, 5), 'c': (3, 6)}

In [18]: dict(zip(list1, map(list, zip(map(int, list2), map(int, list3)))))
Out[18]: {'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}

For an arbitrary number of lists, you could do this:

dict(zip(list1, zip(*(map(int, lst) for lst in (list2, list3, list4, ...)))))

Or, to make the values lists rather than tuples,

dict(zip(list1, map(list, zip(*(map(int, lst) for lst in (list2, list3, list4, ...))))))

Upvotes: 12

Related Questions