Home >Backend Development >Python Tutorial >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]))
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)}
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))
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))
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!