JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Convert two lists into dictionaries in Python

Author:JIYIK Last Updated:2025/05/09 Views:

This tutorial shows how to convert two lists into dictionaries in Python, where one list contains the keys and the other contains the values.


Convert two lists to dictionaries using zip()and in Pythondict()

Python has a built-in function zip()that aggregates iterable data types into a tuple and returns it to the caller. Function dict()Creates a dictionary from a given collection.

key_list = ["name", "age", "address"]
value_list = ["Johnny", "27", "New York"]

dict_from_list = dict(zip(key_list, value_list))
print(dict_from_list)

In this solution, we can convert a list to a dictionary using just one line and two functions.

Output:

{'name': 'Johnny', 'age': '27', 'address': 'New York'}

Convert a list to a dictionary using dictionary comprehension in Python

Dictionary comprehensions are a way to shorten the initialization time of creating dictionaries in Python. Comprehensions are foran alternative to loops, which require multiple lines and variables. Comprehensions do the initialization work in one line.

In this solution, the function zip()will still provide values ​​to the dictionary comprehension. The comprehension will zip()return the key-value pairs for each successive element within the return value of the function as a dictionary.

key_list = ["name", "age", "address"]
value_list = ["Johnny", "27", "New York"]

dict_from_list = {k: v for k, v in zip(key_list, value_list)}
print(dict_from_list)

Another way to convert lists to dictionaries is to use the indexing of the lists, use range()the function to iterate over both lists, and use a comprehension to build a dictionary from the lists.

It assumes that the length of the key list and the value list are the same. In this example, the length of the key list will be the basis for the range.

key_list = ["name", "age", "address"]
value_list = ["Johnny", "27", "New York"]

dict_from_list = {key_list[i]: value_list[i] for i in range(len(key_list))}
print(dict_from_list)

Both comprehension options will give the same output as the previous example.

The only difference between the two solutions is that one uses zip()the function to convert the list into a tuple. The other uses range()the function to iterate over both lists using the current index, forming a dictionary.

Output:

{'name': 'Johnny', 'age': '27', 'address': 'New York'}

forConvert a list to a dictionary using loop in Python

The most straightforward way to implement list-to-dictionary conversion is with a loop. Although this method is the least efficient and most verbose, it is a good place to start, especially if you are a beginner and want to understand more basic programming syntax.

Before the loop, initialize an empty dictionary. Afterwards, proceed with the transformation, which will require a nested loop; the outer loop will iterate over the list of keys, while the inner loop will iterate over the list of values.

key_list = ["name", "age", "address"]
value_list = ["Johnny", "27", "New York"]

dict_from_list = {}
for key in key_list:
    for value in value_list:
        dict_from_list[key] = value
        value_list.remove(value)
        break

print(dict_from_list)

Each time a key-value pair is formed, the value element is removed from the list so that the next key is assigned the next value. After the removal, the inner loop is interrupted and the next key is continued.

Another solution using a loop is to use range()to take advantage of the index to get the key and value pairs, as we did in the dictionary comprehension example.

key_list = ["name", "age", "address"]
value_list = ["Johnny", "27", "New York"]

dict_from_list = {}
for i in range(len(key_list)):
    dict_from_list[key_list[i]] = value_list[i]

print(dict_from_list)

Both solutions will produce the same output.

{"name": "Johnny", "age": "27", "address": "New York"}

To summarize, the most efficient way to convert two lists into a dictionary is to use the built-in function zip()to convert the two lists into a tuple, and then use dict()to convert the tuple into a dictionary.

Using dictionary comprehensions you can also zip()convert a list to a tuple using , or range()convert a list to a dictionary using , which iterates over and initializes a dictionary using the list's indices.

Both of these solutions are much better solutions than the naive solution which uses a normal loop to convert the list to a dictionary.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Finding a string in a list in Python

Publish Date:2025/05/09 Views:75 Category:Python

This tutorial shows you how to find elements from a Python list that have a specific substring in them. We will use the following list and extract ack the strings that have in it. my_list = [ "Jack" , "Mack" , "Jay" , "Mark" ] for Find elem

Getting list shape in Python

Publish Date:2025/05/09 Views:139 Category:Python

In Python, knowing the shape of a list is very important for working with data structures, especially when it comes to multidimensional or nested lists. This article explores various ways to determine the shape of a list in Python, from sim

Adding multiple elements to a list in Python

Publish Date:2025/05/09 Views:180 Category:Python

List is a mutable data structure in Python. It can contain values ​​of different types. This article will discuss some methods to append single or multiple elements to a Python list. append() Append a single element in a Python list usi

Get the index of the maximum and minimum values in a list in Python

Publish Date:2025/05/09 Views:117 Category:Python

In this tutorial, we will discuss methods to get the index of the maximum and minimum value of a list in Python. max() Get the index of the maximum value in a list using and list.index() functions in Python max() The function gives the maxi

List of numbers from 1 to N in Python

Publish Date:2025/05/09 Views:116 Category:Python

This tutorial will discuss how to create a list of numbers from 1 to some specified number. Create a user-defined function to create a list of numbers from 1 to N This method will take the desired number from the user and for iterate until

Convert List to Pandas DataFrame in Python

Publish Date:2025/05/09 Views:133 Category:Python

This article will show you how to convert items in a list into a Pandas DataFrame. Convert List to Pandas DataFrame in Python DataFrame, in general, is a two-dimensional labeled data structure. Pandas is an open source Python package that i

Sorting a list by another list in Python

Publish Date:2025/05/09 Views:148 Category:Python

Normally, when we sort a list, we do it in ascending or descending order. However, we can sort a list based on the order of another list in Python. We will learn how to sort a given list based on the values ​​in another list in this art

Normalizing a list of numbers in Python

Publish Date:2025/05/09 Views:134 Category:Python

Normalization means converting the given data to another scale. We rescale the data so that it is between two values. Most of the time, the data is rescaled between 0 and 1. We rescale data for different purposes. For example, machine learn

How to create a list of a specific size in Python

Publish Date:2025/05/09 Views:195 Category:Python

Preallocating storage for a list or array is a common practice among programmers when they know the number of elements in advance. Unlike C++ and Java, in Python you must initialize all preallocated storage with some value. Typically, devel

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial