dict.items vs dict.iteritems


/ Published in: Python
Save to your folder(s)

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?


Copy this code and paste it in your HTML
  1. # Both seem to work for something like:
  2.  
  3. mydict = {'a' : 1, 'b' : 2}
  4.  
  5. for key,val in mydict.items():
  6. print key,val
  7.  
  8. # ==> a 1 b 2
  9.  
  10. for key,val in mydict.iteritems():
  11. print key,val
  12.  
  13. # ==> a 1 b 2
  14.  
  15. # iteritems and xrange only provide values when requested.
  16. # items and range build complete list when called.
  17.  
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.