How to Convert a Key-Value List to a Flat Dictionary in Python
Converting a list of key-value pairs into a flat dictionary is a fundamental operation in Python, commonly needed when parsing configuration data, processing database query results, transforming API responses, or restructuring data for easier access.
In this guide, you will learn multiple methods to convert key-value lists into flat dictionaries, including lists of tuples, lists of lists, and separate key/value lists. Each method is explained with clear examples and guidance on choosing the right approach.
Understanding the Problem
Given a list where each element contains a key and a value:
data = [("name", "Alice"), ("age", 25), ("city", "NYC")]
The goal is to convert it to a flat dictionary:
{"name": "Alice", "age": 25, "city": "NYC"}
The input can be a list of tuples, lists, or even two separate lists, one for keys and one for values.
Method 1: Using dict() (Recommended)
The most concise and Pythonic approach uses the built-in dict() constructor, which directly accepts an iterable of key-value pairs:
data = [("name", "Alice"), ("age", 25), ("city", "NYC")]
result = dict(data)
print(result)
Output:
{'name': 'Alice', 'age': 25, 'city': 'NYC'}
This works with any iterable of two-element sequences, whether tuples, lists, or other iterables:
# List of lists
data_lists = [["name", "Alice"], ["age", 25], ["city", "NYC"]]
print(dict(data_lists))
# List of tuples
data_tuples = [("name", "Alice"), ("age", 25), ("city", "NYC")]
print(dict(data_tuples))
Output:
{'name': 'Alice', 'age': 25, 'city': 'NYC'}
{'name': 'Alice', 'age': 25, 'city': 'NYC'}
dict() is the fastest and most readable option for straightforward key-value pair conversion. It is implemented in C internally, making it more efficient than Python-level loops or comprehensions for this specific task.
Method 2: Using Dictionary Comprehension
Dictionary comprehension provides a flexible one-liner that allows you to apply transformations or filtering during conversion:
data = [("name", "Alice"), ("age", 25), ("city", "NYC")]
result = {key: value for key, value in data}
print(result)
Output:
{'name': 'Alice', 'age': 25, 'city': 'NYC'}
Applying Transformations During Conversion
The real strength of comprehensions is the ability to modify keys or values as the dictionary is built:
data = [("Name", "alice"), ("Age", "25"), ("City", "nyc")]
# Lowercase keys, capitalize string values, convert numeric strings to int
result = {
key.lower(): int(value) if value.isdigit() else value.capitalize()
for key, value in data
}
print(result)
Output:
{'name': 'Alice', 'age': 25, 'city': 'Nyc'}
Filtering Out Unwanted Pairs
You can add a condition to exclude pairs that do not meet your criteria:
data = [("name", "Alice"), ("temp", None), ("age", 25), ("debug", "")]
# Only include pairs where the value is truthy
result = {key: value for key, value in data if value}
print(result)
Output:
{'name': 'Alice', 'age': 25}
Method 3: Using a for Loop
An explicit loop is the most readable approach and offers full control for validation, error handling, logging, or custom duplicate-key behavior:
data = [("name", "Alice"), ("age", 25), ("city", "NYC")]
result = {}
for key, value in data:
result[key] = value
print(result)
Output:
{'name': 'Alice', 'age': 25, 'city': 'NYC'}
Handling Duplicate Keys
When the input list contains duplicate keys, the last value wins by default in all dictionary-based methods. If you need different behavior, the loop approach gives you full control:
from collections import defaultdict
data = [("color", "red"), ("size", "large"), ("color", "blue"), ("color", "green")]
# Default behavior: last value wins
result_last = dict(data)
print("Last wins:", result_last)
# Keep only the first value for each key
result_first = {}
for key, value in data:
if key not in result_first:
result_first[key] = value
print("First wins:", result_first)
# Collect all values into lists
result_all = defaultdict(list)
for key, value in data:
result_all[key].append(value)
print("All values:", dict(result_all))
Output:
Last wins: {'color': 'green', 'size': 'large'}
First wins: {'color': 'red', 'size': 'large'}
All values: {'color': ['red', 'blue', 'green'], 'size': ['large']}
Method 4: Using zip() with Separate Key and Value Lists
When keys and values are stored in separate lists, use zip() to pair them together before converting:
keys = ["name", "age", "city"]
values = ["Alice", 25, "NYC"]
result = dict(zip(keys, values))
print(result)
Output:
{'name': 'Alice', 'age': 25, 'city': 'NYC'}
If the lists have different lengths, zip() silently stops at the shorter one, which can lead to data loss without any warning:
keys = ["name", "age", "city", "country"]
values = ["Alice", 25]
result = dict(zip(keys, values))
print(result)
# {'name': 'Alice', 'age': 25}
# "city" and "country" are silently dropped!
To catch mismatches, use strict=True (Python 3.10+) or itertools.zip_longest():
keys = ["name", "age", "city", "country"]
values = ["Alice", 25]
# Python 3.10+: raises ValueError on length mismatch
try:
result = dict(zip(keys, values, strict=True))
except ValueError as e:
print(f"Error: {e}")
# Fill missing values with a default instead
from itertools import zip_longest
result = dict(zip_longest(keys, values, fillvalue=None))
print(result)
Output:
Error: zip() argument 2 is shorter than argument 1
{'name': 'Alice', 'age': 25, 'city': None, 'country': None}
Method 5: Using map() with dict()
When key-value pairs are encoded inside strings or other structures that need parsing, map() can extract them before conversion:
# List of strings in "key=value" format
data = ["name=Alice", "age=25", "city=NYC"]
result = dict(map(lambda s: s.split("=", 1), data))
print(result)
Output:
{'name': 'Alice', 'age': '25', 'city': 'NYC'}
The split("=", 1) uses a maxsplit of 1 to ensure that values containing = characters are handled correctly.
Common Mistake: Non-Two-Element Sequences
All methods expect each element to contain exactly two items: a key and a value. Passing sequences of different lengths raises an error:
Incorrect input with three elements per tuple:
data = [("name", "Alice", "extra"), ("age", 25, "unused")]
result = dict(data)
Error:
ValueError: dictionary update sequence element #0 has length 3; 2 is required
Fix by extracting only the first two elements:
data = [("name", "Alice", "extra"), ("age", 25, "unused")]
result = {item[0]: item[1] for item in data}
print(result)
Output:
{'name': 'Alice', 'age': 25}
Converting Nested Key-Value Lists
For deeper nesting where values are themselves lists of key-value pairs, a recursive function converts each level into a dictionary:
def nested_to_dict(data):
"""Convert nested key-value pairs to a nested dictionary."""
result = {}
for key, value in data:
if isinstance(value, list) and all(
isinstance(v, (tuple, list)) and len(v) == 2 for v in value
):
result[key] = nested_to_dict(value)
else:
result[key] = value
return result
data = [
("name", "Alice"),
("address", [("city", "NYC"), ("zip", "10001")]),
("age", 25),
]
print(nested_to_dict(data))
Output:
{'name': 'Alice', 'address': {'city': 'NYC', 'zip': '10001'}, 'age': 25}
Method Comparison
| Method | Best For | Transformations | Duplicate Handling | Performance |
|---|---|---|---|---|
dict() | Simple, direct conversion | No | Last value wins | Fastest |
| Dict comprehension | Conversion with filtering or transformation | Yes | Last value wins | Fast |
for loop | Validation, error handling, custom logic | Yes | Fully customizable | Fast |
zip() + dict() | Separate key and value lists | No | N/A | Fastest |
map() + dict() | Parsing strings into pairs | Limited | Last value wins | Fast |
Conclusion
Converting key-value lists to flat dictionaries in Python is straightforward, with several approaches available depending on your requirements:
- Use
dict()for the simplest and fastest conversion of pre-formatted key-value pairs. - Use dictionary comprehension when you need to filter entries or transform keys and values during conversion.
- Use a
forloop when you need custom duplicate handling, validation, or complex logic. - Use
zip()when keys and values are stored in separate lists, but always verify that both lists have the same length to avoid silent data loss. - Use
map()withdict()when key-value pairs need to be parsed from strings or other raw formats.
Regardless of the method you choose, remember that each element must contain exactly two items, and that duplicate keys cause the last value to win by default unless you implement custom handling.