Condensing two lists of unequal length into a Python dictionary

WBOY
Release: 2023-08-19 11:29:06
forward
1115 people have browsed it

Condensing two lists of unequal length into a Python dictionary

introduce

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

In this article, we will discuss the compression operation of two lists with unequal lengths and output the results as a dictionary. This article will help readers understand the compression operation of a list and generate a dictionary from it.

So let’s start by discussing the implications of compressing two unequal lists.

Compress two lists with unequal lengths

In Python, compression is one of the most common operations when collecting and processing data, and it involves adding two lists in the form of key-value pairs. Simply put, it is an operation where the values or elements in a list are ordered or represented in a way that makes them look like key-value pairs in the output result.

This operation is one of the most common, because sometimes we may need a list or dictionary that is a combination of two different lists. We can have two lists of different sizes or lengths and then merge them and output them in dictionary form for easier and more efficient processing of the data.

There are many ways to achieve the same effect. Let's discuss some of these methods.

Method 1: Using 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))
Copy after login

As we can see in the code above, first we imported cycle from itertools and defined two lists of different sizes.

Then use the loop function in itertools to compress two lists of unequal lengths, and then express the output as a dictionary.

Output

The output of the following code will be:

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

Method 2: Use deque

Like the loop in itertools, we can use the deque in collections. By importing deque, we can compress the two lists and get a 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))
Copy after login

As we can see in the above code, after importing deque from collections, two lists of different sizes are defined.

Then use the for loop and append function to compress the two lists. The final result will be printed in the form of a dictionary.

Output

The output of this code will be:

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

Method 3: Use default class

The default class can also be used to compress two lists of different sizes and give a dictionary as 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)))
Copy after login

As we can see in the above code, two lists are defined after importing the default class and using a for loop to add the values to the corresponding keys.

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

Output

The output of the following code will be:

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

Method 4: Use Zip() Dict()

This is the simplest way to zip two different lists and output them 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))
Copy after login

In the above code, we first define two different lists, then when defining the result, pass the syntax or code to dict(), which will return the output in dictionary data format. Here, two lists are compressed together using the zip keyword, which appends the values of two different lists together.

Output

The output of the following code will be:

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

Method 5: Use Itertools() enumerate()

In this method, we will use the Itertools library and use enumerate in the process of compressing 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))
Copy after login

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

Output

The output of the following code will be:

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

in conclusion

In this article, we discuss using six different methods for compression operations on two lists of different sizes in Python, and provide code examples and instructions. This article will help readers perform similar operations if needed.

The above is the detailed content of Condensing two lists of unequal length into a Python dictionary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!