How To Convert Generator Object To Dictionary In Python
Last Updated :
23 Jul, 2025
We are given a generator object we need to convert that object to dictionary. For example, a = (1, 2, 3), b = ('a', 'b', 'c') we need to convert this to dictionary so that the output should be {1: 'a', 2: 'b', 3: 'c'}.
Using a Generator Expression
A generator expression can be used to generate key-value pairs, which are then passed to the dict() function to create a dictionary. The generator iterates over data, yielding pairs that dict() converts into a dictionary.
Python
a = ((x, x**2) for x in range(5)) # Generator of key-value pairs (x, x^2)
# Convert generator to dictionary
res = dict(a)
print(res)
Output{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Explanation:
- Generator expression ((x, x**2) for x in range(5)) generates key-value pairs where the key is x and the value is x**2 for values of x from 0 to 4.
- dict(a) function converts the generator into a dictionary resulting in a dictionary with the keys and values generated by the expression, such as {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Using zip() and iter()
Using zip(), two iterables (one for keys and one for values) are paired together into key-value tuples and then passing the result to dict() converts these pairs into a dictionary.
Python
a = (1, 2, 3)
b = ('a', 'b', 'c')
# Generator for key-value pairs using zip
gen = zip(a, b)
# Convert to dictionary
res = dict(gen)
print(res)
Output{1: 'a', 2: 'b', 3: 'c'}
Explanation:
- zip(a, b) function pairs elements from the two iterables a and b, creating key-value tuples like (1, 'a'), (2, 'b'), (3, 'c').
- dict(gen) converts these key-value pairs into a dictionary, resulting in {1: 'a', 2: 'b', 3: 'c'}.
Using a Dictionary Comprehension
Using a dictionary comprehension you can directly iterate over the generator to construct a dictionary by assigning each key-value pair. It provides a concise way to transform the generator into a dictionary in one step.
Python
a = (1, 2, 3)
b = ('a', 'b', 'c')
# Generator for key-value pairs using zip
gen = zip(a, b)
# Convert to dictionary using dictionary comprehension
res = {key: value for key, value in gen}
print(res)
Output{1: 'a', 2: 'b', 3: 'c'}
Explanation:
- Generator zip(a, b) pairs elements from the two tuples a and b, creating key-value pairs like (1, 'a'), (2, 'b'), (3, 'c').
- Dictionary comprehension {key: value for key, value in gen} iterates over these pairs and constructs a dictionary, resulting in {1: 'a', 2: 'b', 3: 'c'}
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice