开发者

Suggestions for improving how I loop through the values of a dictionary?

This is what I have been开发者_如何学编程 using:

for i in iter(SHAPES):
    SHAPES[i].drawOrder(97)
    SHAPES[i].alpha(CFG["SHP_alpha"])
    .
    .

This is what I thought about doing:

for i, v in app.SHAPES.items():
    v.drawOrder(97)
    v.alpha(CFG["SHP_alpha"])
    .
    .

Which of the two am I supposed to use? Are there any other ways of doing it?


If you don't need the key, just ignore it and use .itervalues(). If you need both key and value, .iteritems() is indeed the way to go. Note that in Python 3, those got rid of the iter prefix and Python 2 .values() and .items() (which returned lists) are gone. They have their (rare) uses, but when you just iterate, there is no need to copy half of the dictionary.

And never call iter yourself unless you really need an iterator (e.g. for next). Which is hardly more often than never ;) for i in iterable already uses iter(iterable) implicitly.


Iterate over the values in the dict.

for v in SHAPES.itervalues():
    v.drawOrder(97)
    ...


The option that gives the most flexibility for a dictionary is to use enumerate() and dict.iteritems().

for i, (k,v) in enumerate(SHAPES.iteritems()):
   print "My index is {0}, key is {1}, and value is {2}".format(i, k, v)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜