Return to Snippet

Revision: 26933
at November 10, 2010 22:12 by magicrebirth


Updated Code
# Both seem to work for something like:

mydict = {'a' : 1, 'b' : 2}

for key,val in mydict.items():
    print key,val

# ==>  a 1 b 2

for key,val in mydict.iteritems():
    print key,val

# ==>  a 1 b 2

# iteritems and xrange only provide values when requested.
# items and range build complete list when called.
 
# Both work, you may prefer xrange/iteritems for iteration on large
# collections, you may prefer range/items when processing of the result
# value explicitly need a list (ex. calculate its length) or when you are
# going to manipulate the original container in the loop.

Revision: 26932
at May 17, 2010 06:49 by magicrebirth


Initial Code
for key,val in mydict.items():
print key,val

for key,val in mydict.iteritems():
print key,val



iteritems and xrange only provide values when requested.
items and range build complete list when called.

Both work, you may prefer xrange/iteritems for iteration on large
collections, you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length) or when you are
going to manipulate the original container in the loop.

Initial URL


Initial Description
When is it appropriate to use dict.items() vs dict.iteritems?


Also, when is it appropriate to use range() vs xrange(). From my
understanding, xrange() essentially gives you an iterator across a
range, so it should be used when iterating. Should you only use
range() when want to physically store the range as a list?

Initial Title
dict.items vs dict.iteritems

Initial Tags


Initial Language
Python