Hướng dẫn dict(zip in python)

Hướng dẫn dict(zip in python)

The list and dictionary are among the robust data structures in Python. Converting from each other is the most common task you have ever faced in Python development. For example, you often create a dictionary from two different but closely related sequences. An easy way to approach this is to use the dict() and zip() methods together.

To create a dictionary from two sequences, use the dict() and zip() method. The dict(zip(keys, values)) needs the one-time global lookup each for dict and zip. Still, it doesn’t create any needless intermediary data structures or deal with local lookups in function applications.

In Python 3, the zip() method now returns a lazy iterator, the most used approach.

# app.py

stocks = ['reliance', 'infosys', 'tcs']
prices = [2175, 1127, 2750]
dictionary = dict(zip(stocks, prices))
print(dictionary)

Output

{'reliance': 2175, 'infosys': 1127, 'tcs': 2750}

In this example, we have defined two lists that we need to convert into a dictionary. The first list of items will be keys for the dictionary, and the second list of items will be the dictionary.

The zip(fields, values) method returns an iterator that generates two-items tuples. If you call dict() on that iterator, you can create the dictionary you need. The items of the first list become the dictionary’s keys, and the elements second list represent the values in the dictionary.

One important thing to note that dictionary = {zip(keys, values)} will not work. You have to declare as dict(zip()) explicitly. If you make it work, you have to use proper dictionary comprehension.

Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create dictionaries. For example, we can use the above example to create a dictionary from two lists.

The minimal syntax for dictionary comprehension is the following.

dictionary = {key: value for vars in iterable}

See the following code example of dictionary comprehension.

# app.py

stocks = ['reliance', 'infosys', 'tcs']
prices = [2175, 1127, 2750]

new_dict = {stocks: prices for stocks, prices in zip(stocks, prices)}
print(new_dict)

Output

{'reliance': 2175, 'infosys': 1127, 'tcs': 2750}

That is it for the Python zip dictionary example.

There are numerous occasions in Python where a link between two or more iterators is required, such as tuples, dictionaries, lists, and sets. Zipping is the python term for pairing such iterators. In this article, how python zip two lists together.

Lists in python are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not always be homogeneous, which makes it the most powerful tool in Python. To learn more about python lists, visit our article "3 Ways to Find Python List Size".

Using a normal zip function, you can easily aggregate the contents of the container class. There are times, though, when numerous lists and contained lists are required as index components, and you must merge them. This is an odd circumstance, but the solution is straightforward. So, let's see how things work!

How to Zip Two Lists in Python?

Below are the three methods by which python zip two lists:

1) Using the built-in zip() function

Python possesses an extensive collection of in-built methods, one of which is the zip() function. Using the zip() function, you can create an iterator object containing tuples (know more about tuple at "3 Ways to Convert Lists to Tuple in Python"). It can be helpful to think of the zip() function as combining two or more lists (or other iterable objects) into an object containing ordered tuples from the lists. The below example shows how the zip() function can easily merge two lists in python without any extra effort.

For example:

list_a = [1, 3, 4]
list_b = [5, 7, 11]

list_zip = zip(list_a, list_b)

zipped_list = list(list_zip)
print(zipped_list)

Output:

[(1, 5), (3, 7), (4, 11)]

2) Using map() + __add__

map() function is another in-built python method similar to zip() function above. It enables you to zip the elements of the iterable by mapping the elements of the first iterable with the elements of the second iterable. By using the map() function along with the addition operator, you can merge two lists in python as shown in the below example:

list_1 = [[2, 3], [4, 5], [7, 6]]
list_2 = [[4, 9], [4, 2], [11, 10]]
  
print ("The given list 1 is : " + str(list_1))
print ("The given list 2 is : " + str(list_2))
  

res = list(map(list.__add__, list_1, list_2))
      
print ("The zipped list is : " +  str(res))

Output:

The given list 1 is : [[2, 3], [4, 5], [7, 6]]
The given list 2 is : [[4, 9], [4, 2], [11, 10]]
The zipped list is : [[2, 3, 4, 9], [4, 5, 4, 2], [7, 6, 11, 10]]

3) Using 'for' loop with zip() function

You can also zip two lists in python with the combination of zip() function and for loop. It is the least used method where the interlist aggregation can be done with the chain function, while the intralist aggregation can be done with the zip() function. Here, you have to make use of chain() function which is part of python itertools library and therefore, the library is imported using "import" keyword before beginning the source code. Check out the below example for better understanding of this method.

For example:

import itertools
  
list_1 = [[1, 3], [4, 5], [5, 6]]
list_2 = [[11, 9], [16, 2], [4, 10]]
  
print ("The given list 1 is : " + str(list_1))
print ("The given list 2 is : " + str(list_2))
  
res = [list(itertools.chain(*i)) 
       for i in zip(list_1, list_2)]
      
print ("The zipped list is : " +  str(res))

Output:

The given list 1 is : [[1, 3], [4, 5], [5, 6]]
The given list 2 is : [[11, 9], [16, 2], [4, 10]]
The zipped list is : [[1, 3, 11, 9], [4, 5, 16, 2], [5, 6, 4, 10]]

Summary

To summarize, lists are the most used data structure in python language and hence face the difficult situation to zip the elements while programming. In this article, we studied various methods to zip the elements of two lists and you can use any of them according to the different situations you face while coding the program. However, the zip() function is highly used and the most recommended method to zip the lists faster and efficiently.