In Python 2.7, dictionaries have both an iterkeys
method and a viewkeys
method (and similar pairs for values and items), giving two different ways
A dictionary view updates as the dictionary does, while an iterator does not necessarily do this.
This means if you work with the view, change the dictionary, then work with the view again, the view will have changed to reflect the dictionary's new state.
They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. Source
Example:
>>> test = {1: 2, 3: 4}
>>> a = test.iterkeys()
>>> b = test.viewkeys()
>>> del test[1]
>>> test[5] = 6
>>> list(a)
[3, 5]
>>> b
dict_keys([3, 5])
When changes are made to the size, an exception will be thrown:
>>> test = {1: 2, 3: 4}
>>> a = test.iterkeys()
>>> b = test.viewkeys()
>>> test[5] = 6
>>> list(a)
Traceback (most recent call last):
File "", line 1, in
RuntimeError: dictionary changed size during iteration
>>> b
dict_keys([1, 3, 5])
It's also worth noting you can only iterate over a keyiterator once:
>>> test = {1: 2, 3: 4}
>>> a = test.iterkeys()
>>> list(a)
[1, 3]
>>> list(a)
[]
>>> b = test.viewkeys()
>>> b
dict_keys([1, 3])
>>> b
dict_keys([1, 3])