Zipping Two Unequal Length Lists in a Python Dictionary


Introduction

In Python, Lists and dictionaries are one of the most used methods for data collection and processing. There are so many operations related to lists and dictionaries which are commonly used to get the data in the desired form. Sometimes we may also need to zip the two different lists and get the zipped list in the dictionary form.

In this article, we will discuss the zipping operations of two lists having an unequal length and getting the output as a dictionary. This article will help one to get an idea behind the zipping operations of the lists and generate a dictionary from the same.

So let us start our discussion on the meaning of zipping two unequal lists.

Zipping Two Unequal Length Lists

In Python, while collecting and processing the data, zipping is one of the most common operations which involves adding the two lists in the manner of key−value pairs. In simple words, it is the operations, where the values or the elements inside the lists are ordered or represented in such a way that it looks like the key−value pairs in the output result.

This operation is one of the most common ones, as sometimes we may need a list or a dictionary which is a combination of two different lists. We can have two different sizes or lengths list and we can zip it and get the output in the dictionary form in order to play with the data more easily and efficiently.

There are so many methods, using which we can do the same. Let us discuss some of those.

Method 1:Use Itertools + Cycle

We can use the itertools library and can import the cycle in order to zip the two lists and get the dictionary as an output.

# Itertools + Cycle Method 


# Import the cycle from itertools
from itertools import cycle

# define two lists
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = [1, 2, 3, 4]

# zip the lists and pass them into the dictionary form
res = dict(zip(list1, cycle(list2)))

# print the final results
print("Final Output Dictionary : ", str(res))

As we can see in the above code, first we imported the cycle from itertools and then the two different−sized lists has been defined.

Then the cycle from the itertools is used to zip the two unequal−length lists and the output is then represented into the dictionary form.

Output

The output of the following code would be:

Final Output Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}

Method 2: Use deque

Same as the cycle from itertools, we can use the deque from the collections. Here by importing the deque we can zip two lists and get the dictionary.

# using deque for zipping lists

from collections import deque

# define two list that are to be zipped 
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = deque([1, 2, 3, 4])

# zip teh lists using deque
result = {}
for letter in ini_lis1:
  number = ini_lis2.popleft()
  result[letter] = number
  ini_lis2.append(number)


# print the final results
print("Output Dict : ", str(result))

As we can see in the above code that two different−sized list has been defined after importing the deque from collections.

Then the for loop has been used to zip the two lists using append. The final result will be printed in the form of a dictionary.

Output

The output of this code would be:

Output Dict : {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}

Method 3: Use Default Class

The default class can also be used to zip two different−sized lists and get the dictionary as an output.

# using default class method

# import default dict from collections
from collections import defaultdict

# define two lists
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = [1, 2, 3, 4]

# use default dict
result = defaultdict(int)

# add values to the keys respectively
for i in range(len(ini_lis1)):
	result[ini_lis1[i]] += ini_lis2[i % len(ini_lis2)]

# print the final results
print("Output Dict: ", str(dict(result)))

As we can see in the above code that two lists have been defined after importing the default class and a for loop is used in order to add the values to the corresponding keys.

Here note that it will return a default value if the key is not present in the data. Here we are taking the default value of 0.

Output

The output of the following code would be:

Output Dict: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}

Method 4: Use Zip() + Dict()

It is one of the simplest methods to zip two different lists and get the output as a dictionary.

# using zip + dict method
# define two lists that are to be zipped
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = [1, 2, 3, 4]

# use zip()
result = dict(zip(ini_lis1, ini_lis2 *
        ((len(ini_lis1) + len(ini_lis2) - 1) // len(ini_lis2))))

# print the final results
print("Output Dict: ", str(result))

Here as we can see in the above code, we are first defining the two different lists, and then while defining the result the syntax or the code is passed into the dict(), which will return an output in the dictionary data format. To zip the two lists here, the zip keyword has been used which appends the values of two different lists.

Output

The output of the following code would be:

Output Dict: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}

Method 5: Using Itertools() + enumerate()

In this method, we will use the Itertools library with using the enumerate in the process of zipping the two lists.

# using itertools + enumerate
# Import itertools
from itertools import cycle

# define two lists
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = [1, 2, 3, 4]

# zip the two lists using for loop and enumerate
result = {v: ini_lis2[i % len(ini_lis2)]
    for i, v in enumerate(ini_lis1)}

# print the final results
print("Output Dict : ", str(result))

As we can see in the above code, we first import the cycle from itertools and then define the two different−sized lists. Then using the for loop and the enumerate function, we are adding up the values or the elements of two different lists (zipping) and then these values are represented in the form of a dictionary.

Output

The output of the following code would be:

Output Dict : {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}

Conclusion

In this article, we discussed the zipping operations of two different−sized lists in Python with six different approaches with code examples and explanations. This article will help one to perform similar operations whenever necessary.

Updated on: 27-Jul-2023

469 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements