How to Zip a Dictionary in Python

Here are four ways to zip a dictionary in Python:

  1. Zip Keys and Values Together
  2. Zip Dictionary with Dictionary
  3. Zip Dictionary with List
  4. 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

Zip Keys and Values Together

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

Using dict()

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}

1 thought on “How to Zip a Dictionary in Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.