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:
a c b
intead of the sorted a b c
, which is supposed to be the case since we are talking about dictionary keys.d = {'a':1, 'b':2, 'c':3}
, and then for a,b,c in d:
, this will be a valueError.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]:
...