As Tordek says, you can use items()
or iteritems()
in this case to avoid the issue:
colprint(sorted((name, packages[0].summary or '')
for (name, packages) in versions.items()))
Moving the sorting outside is a nice touch.
[Note that the use of items()
changed the sorting order slightly - it used to be by name with ties resolved by original order (Python sort is stable), now it's by name with ties resolved by summary. Since the original order of a dict is random, the new behaviour is probably better.]
But for other uses (such as Alex Martelli's example), a "let"-alike might still be useful.
I've also once discovered the for var in [value]
trick, but I now find it ugly.
A cleaner alternative might be a "pipeline" of comprehensions / generators, using the "decorate/undecorate" trick to pass the added value in a tuple:
# You could write this with keys() or items() -
# I'm just trying to examplify the pipeline technique.
names_packages = ((name, versions[name][0])
for name in versions.keys())
names_summaries = ((name, package.summary or '')
for (name, package) in names_packages)
colprint(sorted(names_summaries))
Or applied to Alex's example:
ys = (somefun(z) for z in zs)
xs = [(y, y*1.2, y-3.4) for y in ys]
(in which you don't even need the original z
values, so the intermediate values don't have to be tuples.)
See http://www.dabeaz.com/generators/ for more powerful examples of the "pipeline" technique...