Converting a list of lists into a list of dictionaries is a common task in Python, especially when dealing with data parsing or data transformation tasks. The challenge involves taking an input like [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]]
and converting it into an output like [{"key1": "value1"}, {"key2": "value2"}, {"key3": "value3"}]
. This article explores several methods to achieve this conversion efficiently.
Method 1: Using for-loop and dict()
This method involves iterating over the list of lists using a for-loop and creating a dictionary for each inner list using the dict()
constructor. This is the most straightforward approach that is easy to understand and read, making it a solid choice for beginners.
Here’s an example:
list_of_lists = [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]] list_of_dicts = [] for sublist in list_of_lists: key, value = sublist list_of_dicts.append({key: value})
Output: [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
The code iterates over each list in list_of_lists
, unpacks its elements into key
and value
, and appends a new dictionary with this key-value pair to list_of_dicts
.
Method 2: Using List Comprehension
List comprehension offers a more concise way to achieve the same result as a for-loop. This method is Pythonic and often recommended for its cleaner syntax and readability when dealing with simple transformations.
Here’s an example:
list_of_lists = [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]] list_of_dicts = [{key: value} for key, value in list_of_lists]
Output: [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
We create a list of dictionaries in a single line of code by iterating over each pair of key
, value
in the list_of_lists
and constructing a dictionary for each.
Method 3: Using the map() Function
The map()
function is used to apply a given function to each item of an iterable (like a list) and return a list of results. In this case, we can use map()
with a lambda function to convert each inner list into a dictionary.
Here’s an example:
list_of_lists = [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]] list_of_dicts = list(map(lambda x: {x[0]: x[1]}, list_of_lists))
Output: [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
The lambda
function takes each element x
from the input list and converts it into a dictionary with the first element as the key and the second element as the value.
Method 4: Using zip() When Keys and Values Are Separated
When you have separate lists for keys and values, zip()
can be used to combine them into a list of dictionaries. The zip()
function combines the corresponding elements from each of the iterables into tuples, which can then be turned into a dictionary.
Here’s an example:
keys = ["key1", "key2", "key3"] values = ["value1", "value2", "value3"] list_of_dicts = [dict([pair]) for pair in zip(keys, values)]
Output: [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
Using zip()
returns an iterable of tuples that are then turned into dictionaries inside a list comprehension, creating our list of dictionaries.
Bonus One-Liner Method 5: Using Dictionary Comprehension with enumerate()
Dictionary comprehension with enumerate()
is a convenient one-liner that combines the indexing power of enumerate()
with the elegant syntax of dictionary comprehension. This is useful when you need to convert a list of values into a list of single-key dictionaries with the index as the key.
Here’s an example:
values = ["value1", "value2", "value3"] list_of_dicts = [{i: v} for i, v in enumerate(values)]
Output: [{0: 'value1'}, {1: 'value2'}, {2: 'value3'}]
Using enumerate()
, we get each value accompanied by its index, and for each pair, we create a dictionary where the index is the key and the value is, well, the value.
Summary/Discussion
- Method 1: For-loop with dict(). Strengths: Intuitive and easy for beginners. Weaknesses: More verbose than other methods.
- Method 2: List Comprehension. Strengths: Concise and Pythonic. Weaknesses: Less readable for those unfamiliar with list comprehensions.
- Method 3: Map with lambda. Strengths: Functional programming style, good for single-expression transformations. Weaknesses: Can be unclear to those not comfortable with lambda functions and map.
- Method 4: Using zip() with separate key/value lists. Strengths: Ideal when keys and values are in separate lists and need to be paired. Weaknesses: Less intuitive when working with a single nested list.
- Method 5: Dictionary Comprehension with enumerate(). Strengths: Great for creating indexed dictionaries from a value list. Weaknesses: Only suitable when keys are intended to be indices.