Python How to Convert List of Tuples to Dictionary
dict() function like this: dict(list_of_tuples).Examples
How to Think About It
dict() function, Python automatically pairs these up to create the dictionary.Algorithm
Code
list_of_tuples = [('a', 1), ('b', 2), ('c', 3)] dictionary = dict(list_of_tuples) print(dictionary)
Dry Run
Let's trace converting [('a', 1), ('b', 2)] to a dictionary.
Start with list
list_of_tuples = [('a', 1), ('b', 2)]
Convert using dict()
dictionary = dict(list_of_tuples)
Result
dictionary = {'a': 1, 'b': 2}
| Tuple | Key | Value | Dictionary after step |
|---|---|---|---|
| ('a', 1) | a | 1 | {'a': 1} |
| ('b', 2) | b | 2 | {'a': 1, 'b': 2} |
Why This Works
Step 1: Using dict() function
The dict() function takes an iterable of pairs and creates a dictionary by using the first element as the key and the second as the value.
Step 2: Pairs from tuples
Each tuple in the list represents one key-value pair, so the function reads them one by one.
Step 3: Resulting dictionary
The output is a dictionary where keys are unique and values are assigned from the tuples.
Alternative Approaches
list_of_tuples = [('a', 1), ('b', 2)] dictionary = {} for key, value in list_of_tuples: dictionary[key] = value print(dictionary)
list_of_tuples = [('a', 1), ('b', 2)] dictionary = {k: v for k, v in list_of_tuples} print(dictionary)
Complexity: O(n) time, O(n) space
Time Complexity
The conversion loops through each tuple once, so it takes linear time proportional to the number of tuples.
Space Complexity
A new dictionary is created with the same number of key-value pairs, so space grows linearly with input size.
Which Approach is Fastest?
Using dict() is the fastest and most readable. Manual loops or comprehensions add flexibility but are slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| dict() function | O(n) | O(n) | Simple and fast conversion |
| For loop | O(n) | O(n) | When extra processing needed |
| Dictionary comprehension | O(n) | O(n) | Concise with filtering or transformation |
dict() directly on the list of tuples for the simplest conversion.