When to use iteritems() vs items() in Python 3?

So, I’ve worked a fair bit with Python 2.x and 3.x, and I can tell you, the behavior of .items() changed significantly between the two versions. In Python 2.x, .items() returned a list of (key, value) pairs. But in Python 3.x, .items() now returns an itemview object, which is a bit different. It doesn’t behave like a list by default, so if you want to work with it like in Python 2.x, you’d need to convert it to a list using list(dict.items()).

For backward compatibility, Python 2.7 has these methods like viewkeys, viewitems, and viewvalues. If I had to pick, viewkeys is super handy when you want to do set operations, like finding common keys between two dictionaries:

common_keys = list(dict_a.viewkeys() & dict_b.viewkeys())

In Python 3.x, we don’t need these back-ported methods. You can just use .keys() for key views and .items() for iterating over the dictionary lazily. That’s the big thing with Python 3—it’s all about a “lazy” approach. You don’t have to worry about iteritems() Python 3 anymore, which makes it cleaner to work with.