Home > Backend Development > Python Tutorial > How Can I Efficiently Convert a Flat List of Key-Value Pairs into a Dictionary in Python?

How Can I Efficiently Convert a Flat List of Key-Value Pairs into a Dictionary in Python?

Linda Hamilton
Release: 2024-12-04 18:37:15
Original
525 people have browsed it

How Can I Efficiently Convert a Flat List of Key-Value Pairs into a Dictionary in Python?

Converting a Flat List to a Dictionary

In Python, converting a list of key-value pairs into a dictionary can be achieved in several ways. The simplest approach is to use the dict() function. For instance, given the list a = ['hello', 'world', '1', '2'], we can create the dictionary b using the following syntax:

b = dict(zip(a[::2], a[1::2]))
Copy after login

This line of code uses the zip() function to create a list of tuples, where each tuple contains a key and its corresponding value. The dict() function then converts this list of tuples into a dictionary.

Another method for converting the list to a dictionary is to use a dictionary comprehension. This approach is more concise and easier to read, especially for larger lists:

b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
Copy after login

This comprehension iterates over the list a in pairs and assigns the first element to the key and the second element to the value.

If the list is very large, you may want to avoid creating intermediate lists. In such cases, you can use the itertools.izip() function to iterate over the list lazily, without creating a temporary list. The syntax for this approach is:

from itertools import izip
i = iter(a)
b = dict(izip(i, i))
Copy after login

In Python 3, the zip() function is already lazy, so you don't need to use izip(). You can also use the "walrus" operator (:=) to write this on one line:

b = dict(zip(i := iter(a), i))
Copy after login

The above is the detailed content of How Can I Efficiently Convert a Flat List of Key-Value Pairs into a Dictionary in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template