Here are four ways to zip a dictionary in Python:
- Zip Keys and Values Together
- Zip Dictionary with Dictionary
- Zip Dictionary with List
- Using dict()
Method 1: Zip Keys and Values Together
If you want to create a list of tuples where each tuple is a key-value pair, you can use the zip() function along with the dictionary’s keys() and values() methods.
Visual Representation
Example
new_dict = {'A': 1, 'B': 2, 'C': 3}
zipped = list(zip(new_dict.keys(), new_dict.values()))
print(zipped)
Output
[('A', 1), ('B', 2), ('C', 3)]
Method 2: Zip Dictionary with Dictionary
The zip() function pairs elements from corresponding positions in the two iterables, and list() is used to convert the result into a list format.
Example
new_dict = {'A': 1, 'B': 2, 'C': 3}
other_dict = {'D': 4, 'E': 5, 'F': 6}
zipped = list(zip(new_dict.items(), other_dict.items()))
print(zipped)
Output
[(('A', 1), ('D', 4)), (('B', 2), ('E', 5)), (('C', 3), ('F', 6))]
Method 3: Zip Dictionary with List
This method works the same as the above method; the only difference is that it combines the items of the dictionary with the elements of the list.
Example
new_dict = {'A': 1, 'B': 2, 'C': 3}
new_list =[4, 5, 6]
zipped = list(zip(new_dict.items(), new_list))
print(zipped)
Output
[(('A', 1), 4), (('B', 2), 5), (('C', 3), 6)]
Method 4: Using dict()
The zip() function pairs elements from both lists, producing an iterable of tuples.
The dict() then takes these tuples and creates a dictionary where elements from the first list are the dictionary keys and elements from the second list are the corresponding values.
Visual Representation
Example
new_list = ['A', 'B', 'C']
other_list = [1, 2, 3]
zipped_dict = dict(zip(new_list, other_list))
print(zipped_dict)
Output
{'A': 1, 'B': 2, 'C': 3}
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
print(dict(list(enumerate(my_list))))