Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Yield Dict Elements in generators?

Dict comprehensions do work like list/set comprehensions and generator expressions - an X comprehension with a "body" of expr for vars in iterable is pretty much equivalent to X(expr for vars in iterable) - and you already know how to turn a generator expression into a generator. But note the "pretty much" bit, as a literal translation doesn't work (as you noticed) and isn't necessary at all (doesn't make the implementation much easier and would actually be quite hacky).

Dict comprehension just have a tiny bit of syntactic sugar to look more like dict literals (the colon). Semantically, it's not necessary - there is nothing special about it. Stop and think about it for a second: The dict comprehension must produce two values on each iteration, a key and a value. That's exactly what the colon stands for - (key, value) pairs (remember that dict accepts an iterable of (key, value) pairs). You can't use that syntactic sugar outside of dict comprehensions, but you can just use tuples for the pairs. Therefore, the equivalent generator would be:

def one_to_three_doubles():
    for num in range(1, 4):
        yield num, num * 2

I wanted to generate a dict from yield in a python function and found this question. Below is code for returning a dict.

def _f():
    yield 'key1', 10
    yield 'key2', 20

def f(): return dict(_f())

print(f())
# Output:
{'key1': 10, 'key2': 20}