Search code examples
pythonpython-2.7generatoriterable-unpacking

Unpacking generator which yields a dictionary


I cannot understand the output of the following sample code:

def g1():
    d = {'a':1, 'b':2, 'c':3}
    yield d

for a,b,c in g1():
    print a,b,c

In Python 2.7.14, the above would print out

a c b

There are two interesting aspects of this behavior:

  1. That it prints out a c b intead of the sorted a b c, which is supposed to be the case since we are talking about dictionary keys.
  2. If you just define the dictionary without writing the generator d = {'a':1, 'b':2, 'c':3}, and then for a,b,c in d:, this will be a valueError.

Solution

  • First point: dicts simply aren't ordered in Python 2.7. Don't rely on it until 3.7+.

    Second point: The generator g1(), when iterated, yielded a dictionary. The proposed alternative:

    for a,b,c in d:
        ...
    

    is apples to oranges, this is iterating the dictionary itself. For an equivalent duck to unpack here, you'll need an object which returns a dictionary when iterated:

    for a,b,c in [d]:
        ...