I have the following code, which just print the key/value pairs in a dict (the pairs are sorted by keys):
for word, count in sorted(count_words(filename).items()):
print word, count
However, calling iteritems() instead of items() produces the same output
for word, count in sorted(count_words(filename).iteritems()):
print word, count
Now, which one should I choose in this situation? I consulted the Python tutorial but it doesn’t really answer my question.
In Python 2.x both will give you the same result. The difference between them is that
itemsconstructs a list containing the entire contents of the dictionary whereasiteritemsgives you an iterator that fetches the items one at a time. In generaliteritemsis a better choice because it doesn’t require so much memory. But here you are sorting the result so it probably won’t make any significant difference in this situation. If you are in doubtiteritemsis a safe bet. If performance really matters then measure both and see which is faster.In Python 3.x
iteritemshas been removed anditemsnow does whatiteritemsused to do, solving the problem of programmers wasting their time worrying about which is better. 🙂As a side note: if you are counting occurrences of words you may want to consider using
collections.Counterinstead of a plain dict (requires Python 2.7 or newer).