简体   繁体   中英

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 acb intead of the sorted abc , 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.

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]:
    ...

1.) In Python 2.7, dictionaries are unordered.

2.) for a,b,c in d: will give you an error because you're trying to unpack just the keys of the dictionary into three variables, which won't work. You could however do for a, b in d.items() as it returns a list of tuple pairs.

Colin's answer pretty much answer your questions. But if you want to solve your first problem with unordered list, try using built in class OrderedDict under collections library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM