Why do you have to call items() to iterate over key, value pairs in a dictionary? ie.
dic = {'one': '1', 'two': '2'}
for k, v in dic.items():
print(k, v)
Why isn’t that the default behavior of iterating over a dictionary
for k, v in dic:
print(k, v)
For every python container C, the expectation is that
will pass just fine — wouldn’t you find it astonishing if one sense of
in(the loop clause) had a completely different meaning from the other (the presence check)? I sure would! It naturally works that way for lists, sets, tuples, …So, when
Cis a dictionary, ifinwere to yield key/value tuples in aforloop, then, by the principle of least astonishment,inwould also have to take such a tuple as its left-hand operand in the containment check.How useful would that be? Pretty useless indeed, basically making
if (key, value) in Ca synonym forif C.get(key) == value— which is a check I believe I may have performed, or wanted to perform, 100 times more rarely than whatif k in Cactually means, checking the presence of the key only and completely ignoring the value.On the other hand, wanting to loop just on keys is quite common, e.g.:
having the value as well would not help particularly:
actually somewhat less clear and less concise. (Note that
itemswas the original spelling of the “proper” methods to use to get key/value pairs: unfortunately that was back in the days when such accessors returned whole lists, so to support “just iterating” an alternative spelling had to be introduced, anditeritemsit was — in Python 3, where backwards compatibility constraints with previous Python versions were much weakened, it becameitemsagain).