Last Updated : 07 Apr, 2025
Converting a list of tuples into a dictionary involves transforming each tuple, where the first element serves as the key and the second as the corresponding value. For example, given a list of tuples a = [("a", 1), ("b", 2), ("c", 3)], we need to convert it into a dictionary. Since each key-value pair from the tuples matches a valid dictionary structure, the expected output is {'a': 1, 'b': 2, 'c': 3}. Let's explore different methods to achieve this.
Using dict()dict() function converts an iterable of key-value pairs, such as a list of tuples, into a dictionary. It assigns the first element of each tuple as the key and the second as the corresponding value.
Python
a = [("a", 1), ("b", 2), ("c", 3)]
res = dict(a)
print(res)
{'a': 1, 'b': 2, 'c': 3}
Explanation: dict(a) constructor iterates through the list of tuples a , extracting the first element of each tuple as a key and the second as its corresponding value, forming a dictionary.
Using dictionary comprehensionDictionary comprehension allows creating a dictionary in a single line by iterating over an iterable and specifying key-value pairs. It uses the syntax {key: value for item in iterable} to construct the dictionary efficiently.
Python
a = [("a", 1), ("b", 2), ("c", 3)]
res = {key: value for key, value in a}
print(res)
{'a': 1, 'b': 2, 'c': 3}
Explanation: {key: value for key, value in a} iterates through each tuple, assigning the first element as the key and the second as the value, efficiently constructing a dictionary.
Using for loopUsing a for
loop to create a dictionary involves iterating over an iterable and adding each element as a key-value pair. This can be done by manually assigning values to a dictionary within the loop.
a = [("a", 1), ("b", 2), ("c", 3)]
res = {}
# Populate the dictionary
for key, value in a:
res[key] = value
print(res)
{'a': 1, 'b': 2, 'c': 3}
Explanation: for loop iterates through each tuple, assigning the first element as the key and the second as the value. Each key-value pair is added to res, constructing the dictionary.
Using map() with dict()map() function applies a given function to each element in an iterable, and when used with dict(), it transforms the result into key-value pairs. This allows for efficient mapping and conversion into a dictionary.
Python
a = [("a", 1), ("b", 2), ("c", 3)]
res = dict(map(lambda x: (x[0], x[1]), a))
print(res)
{'a': 1, 'b': 2, 'c': 3}
Explanation: map() function applies a lambda function to each tuple, extracting the first element as the key and the second as the value. The dict() constructor then converts the mapped key-value pairs into a dictionary.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4