Last Updated : 12 Jul, 2025
We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age': 25, 'city': 'NYC'}. For this we can use multiple method like dict, loop with various approach.
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.
Python
a = [("name", "Alice"), ("age", 25), ("city", "New York")] # List of key-value pairs as tuples
# Convert the list of key-value pairs into a flat dictionary using the dict() constructor
res = dict(a)
print(res)
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Explanation:
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.
Python
a = [("name", "Alice"), ("age", 25), ("city", "New York")]
b = {}
for key, value in a:
b[key] = value
print(b)
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Explanation:
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", "Alice"), ("age", 25), ("city", "New York")] # List of key-value pairs as tuples
# Use dictionary comprehension to create a dictionary by unpacking each tuple into key and value
res = {key: value for key, value in a}
print(res)
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Explanation:
a
, unpacking each tuple into key
and value
.key
is mapped to its corresponding value
, and the comprehension directly constructs the dictionary res.
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 = ["Alice", 25, "New York"] # List of values
# Use zip to pair each key from 'a' with the corresponding value from 'b', then convert the pairs to a dictionary
res = dict(zip(a, b))
print(res)
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Explanation:
zip()
function combines elements from the lists a
(keys) and b
(values) into key-value pairs.dict()
constructor then converts the paired elements into a dictionary, mapping each key to its corresponding value.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