A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-convert-key-values-list-to-flat-dictionary/ below:

Python - Convert key-values list to flat dictionary

Python - Convert key-values list to flat dictionary

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)  

Output
{'name': 'Alice', 'age': 25, 'city': 'New York'}

Explanation:

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.

Python
a = [("name", "Alice"), ("age", 25), ("city", "New York")]

b = {}
for key, value in a:
    b[key] = value

print(b)

Output
{'name': 'Alice', 'age': 25, 'city': 'New York'}

Explanation:

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

Python
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)

Output
{'name': 'Alice', 'age': 25, 'city': 'New York'}

Explanation:

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().

Python
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) 

Output
{'name': 'Alice', 'age': 25, 'city': 'New York'}

Explanation:



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