![]() |
VOOZH | about |
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'}.
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.
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Explanation:
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.
{1: 'a', 2: 'b', 3: 'c'}
Explanation:
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.
{1: 'a', 2: 'b', 3: 'c'}
Explanation: