Posted By

magicrebirth on 05/17/10


dictionary items iteritems

Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


dict.items vs dict.iteritems

 / Published in: Python

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?

  1. # Both seem to work for something like:
  3. mydict = {'a' : 1, 'b' : 2}
  5. for key,val in mydict.items():
  6. print key,val
  8. # ==> a 1 b 2
  10. for key,val in mydict.iteritems():
  11. print key,val
  13. # ==> a 1 b 2
  15. # iteritems and xrange only provide values when requested.
  16. # items and range build complete list when called.
  18. # Both work, you may prefer xrange/iteritems for iteration on large
  19. # collections, you may prefer range/items when processing of the result
  20. # value explicitly need a list (ex. calculate its length) or when you are
  21. # going to manipulate the original container in the loop.

Report this snippet  


RSS Icon Subscribe to comments
Posted By: Jacky888 on October 24, 2018

the 8 best air purifier for pollution airpurifiers-review

You need to login to post a comment.