Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 760
user1919 Avatar asked Apr 05 '13 12:04

user1919


People also ask

How do I create a dictionary in multiple lists?

By using the zip() and dict() method we will create a dictionary from two lists. In this example, we will pass two iterable items as an argument that is 'to_lis1' and 'to_lis2'. Now we will convert this iterator into a dictionary key-value element by using the dict() method.

How do I map multiple lists in Python?

The map() function is a built-in function in Python, which applies a given function to each item of iterable (like list, tuple etc) and returns a list of results or map object. Note : You can pass as many iterable as you like to map() function.

Can you append a list to a dictionary?

Method 5: Adding a list directly to a dictionary. You can convert a list into a value for a key in a python dictionary using dict() function.


1 Answers

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, ...))))))
like image 167
unutbu Avatar answered Nov 07 '22 20:11

unutbu