The Power of Zipping and Unpacking in Python
This article will teach you about the built-in functionality that can turn two lists into a dictionary. …
This article will teach you about the built-in functionality that can turn two lists into a dictionary.
Python’s built-in zip function allows us to iterate over multiple lists simultaneously. You may have seen it used with two lists, like this:
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
for item in zip(list1, list2):
print(item) # prints ('a', 1), ('b', 2), ('c', 3)
You can easily turn the result of a zip()
into a dictionary by using Python’s unpacking syntax:
dict_from_lists = dict(zip(list1, list2)) # {'a': 1, 'b': 2, 'c': 3}
In this way, the first elements of all input lists are paired together to form a dictionary. This can be useful when you have multiple lists representing different aspects of one thing and you want them combined into a single object.
Another approach is using the fromkeys()
method. It creates a new dictionary where keys are from an iterable and values are all the same (default is None):
list1 = ['a', 'b', 'c']
value = 10
dictionary = dict.fromkeys(list1, value) # {'a': 10, 'b': 10, 'c': 10}
In this way, all keys in the list get mapped to the same value. This can be useful if you want a dictionary with certain keys but not concerned about their values.