Python zip dictionaries

Python zip dictionaries

If you are looking for information about Python zip dictionaries, read our article. We will explain the zip() function and give you some examples using the function with dictionaries.

What is the zip() in Python?

The zip() function merges iterable objects’ elements by their orders and returns a zip object. The zip object can be used to create a new iterable object with a length equal to the shortest length of one of the iterable objects.

Syntax:

zip(object1, object2, … objectn)

Parameter:

  • object1, object2, … objectn: Same of different iterable objects.

For example, we will create a list after zipping a list, set, and tuple.

mySet = {"Blue", "Red", "White"}
myTuple = ("Tiger", "Lion", "Elephant")
myList = ["Apple", "Banana", "Berry"]
 
# Zip the set, tuple and list
myZip = zip(mySet, myTuple, myList)
 
# Create and print the new list from the zip object
print(list(myZip))

Result:

[('Blue', 'Tiger', 'Apple'), ('White', 'Lion', 'Banana'), ('Red', 'Elephent', 'Berry')]

Python Zip dictionaries 

Create a dictionary from the zip object

Because a dictionary object is a pair of keys and values, we can only zip two iterable objects to create a dictionary. All the first object’s elements will be converted into the keys, and the second ones will be converted into values. Look at the following example for detailed implementation.

Code:

object = ["Sky", "Cloud", "Sunshine"]
color = ["Blue", "White", "Yellow"]
 
# Create a zip object
zipObject = zip(object, color)
 
# Create a dictionary from the zip object
myDict = dict(zipObject)
 
print(myDict)

Result:

{'Sky': 'Blue', 'Cloud': 'White', 'Sunshine': 'Yellow'}

Zip dictionaries with the same keys

In some situations, if you want to zip dictionaries’ values with the same keys, make sure that the order of their keys is the same. Then, follow the steps below.

  • Step 1: Zip all the dictionaries’ values together.
  • Step 2: Zip the dictionaries’ keys and the zip object above.
  • Step 3: Create a dictionary from the two zip objects above.

Code:

dict1 = {"Snake": "Reptiles", "Parrot": "Birds", "Lion ": "Mammal"}
dict2 = {"Snake": "No leg", "Parrot": "2 legs", "Lion ": "4 legs"}
 
# Zip two dictionaries' values
character = zip(dict1.values(), dict2.values())
 
# Zip keys and characters
animals = zip(dict1.keys(), character)
 
# Create a dictionary from the zip object
animals = dict(animals)
 
print(animals)

Result:

{'Snake': ('Reptiles', 'No leg'), 'Parrot': ('Birds', '2 legs'), 'Lion ': ('Mammal', '4 legs')}

Summary

In summary, the zip() function can merge elements of different iterable objects into a zip object. We can create a dictionary from the zip object or use the zip() function to zip many objects with the same keys. We hope our article about Python zip dictionaries is helpful for you. Good luck!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *