Python - Convert Key-Values List to Flat Dictionary
Given a list of key-value pairs, the task is to convert it into a flat dictionary. For example:
Input: [("name", "Ak"), ("age", 25), ("city", "NYC")]
Output: {'name': 'Ak', 'age': 25, 'city': 'NYC'}
Below are multiple methods to convert a key-value list into a dictionary efficiently.
Using dict()
dict() constructor converts a list of key-value pairs into a dictionary by using each sublist's first element as a key and the second element as a value. This results in a flat dictionary where the key-value pairs are mapped accordingly.
a = [("name", "Emma"), ("age", 25), ("city", "New York")]
res = dict(a)
print(res)
Output
{'name': 'Emma', 'age': 25, 'city': 'New York'}
Using Dictionary Comprehension
Dictionary comprehension {key: value for key, value in a} iterates through the list a, unpacking each tuple into key and value. It then directly creates a dictionary by assigning the key to its corresponding value.
a = [("name", "Emma"), ("age", 25), ("city", "New York")]
res = {key: value for key, value in a}
print(res)
Output
{'name': 'Emma', 'age': 25, 'city': 'New York'}
Using a Loop
For loop iterates through each tuple in the list 'a', extracting the key and value, and then adds them to a dictionary. The dictionary is built incrementally by mapping each key to its corresponding value.
a = [("name", "Emma"), ("age", 25), ("city", "New York")]
b = {}
for key, value in a:
b[key] = value
print(b)
Output
{'name': 'Emma', 'age': 25, 'city': 'New York'}
Explanation:
- for loop iterates through each tuple in the list a, unpacking it into key and value.
- In each iteration, the key is used to assign the value to the dictionary b, effectively constructing the dictionary
Using zip()
zip() function pairs the keys from a with corresponding values from b, creating key-value pairs. These pairs are then converted into a dictionary using dict().
a = ["name", "age", "city"] # List of keys
b = ["Emma", 25, "New York"] # List of values
res = dict(zip(a, b))
print(res)
Output
{'name': 'Emma', 'age': 25, 'city': 'New York'}
Explanation:
- zip(keys, values) creates an iterator of key-value tuples.
- dict() converts these tuples into a dictionary.