Using .items()
to iterate over a dictionary and then discarding either the key or the value in each iteration is less efficient than
directly iterating over only the keys or values needed.
Python dictionaries provide efficient ways to iterate over their contents:
- Iterating directly over the dictionary yields the keys:
for k in my_dict:
...
- Using
my_dict.keys()
explicitly yields the keys.
- Using
my_dict.values()
yields the values.
- Using
my_dict.items()
yields key-value pairs (as tuples).
The .items()
method is useful when you need both the key and the value within the loop. However, if your loop only uses the key,
discarding the value, often with _
, or only uses the value, discarding the key, calling .items()
performs unnecessary work
retrieving the part you don’t use.
While the performance difference might be minor for small dictionaries, using the more specific method is clearer, more idiomatic, and avoids
retrieving and unpacking data that is immediately ignored, like`.keys()` for keys, or .values()
for values.