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?
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.
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.
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.
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, ...))))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With