PYTHON

Convert List of Tuples to Dictionary in Python

Efficiently transform a list of key-value pair tuples into a dictionary using Python's `dict()` constructor or a dictionary comprehension for quick and flexible data restructuring.

# Example list of tuples, where each tuple is a key-value pair
student_grades_tuples = [
    ('Alice', 'A'),
    ('Bob', 'B+'),
    ('Charlie', 'A-'),
    ('David', 'C')
]

# Method 1: Using the dict() constructor (most common and Pythonic)
grades_dict_constructor = dict(student_grades_tuples)
print(f"Using dict() constructor: {grades_dict_constructor}")

# Method 2: Using a dictionary comprehension (useful for transformations or filtering during conversion)
# Let's say we only want students with grade 'A' or 'A-'
grades_dict_comprehension = {
    student: grade for student, grade in student_grades_tuples
    if grade.startswith('A')
}
print(f"Using dict comprehension (filtered): {grades_dict_comprehension}")

# Example with different data
user_settings_tuples = [
    ('theme', 'dark'),
    ('notifications', True),
    ('language', 'en')
]
settings_dict = dict(user_settings_tuples)
print(f"User settings: {settings_dict}")
How it works: Converting a list of key-value pair tuples into a dictionary is a frequent requirement when structuring data. Python offers very straightforward methods for this. The most direct and Pythonic approach is to simply pass the list of tuples to the `dict()` constructor; it automatically interprets each tuple as a `(key, value)` pair. Alternatively, a dictionary comprehension provides more flexibility. You can use it to perform transformations on keys or values, or to filter the items during the conversion process, only including tuples that meet specific criteria. Both methods are highly efficient and produce a clean dictionary suitable for O(1) lookups.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs