Dictionary View Iterators

As we saw briefly in Chapter 8, in Python 3.0 the dictionary keys, values, and items methods return iterable view objects that generate result items one at a time, instead of producing result lists all at once in memory. View items maintain the same physical ordering as that of the dictionary and reflect changes made to the underlying dictionary. Now that we know more about iterators, here's the rest of the story:

>>> K = D.keys() # A view object in 3.0, not a list

<dict_keys object at 0x026D83C0>

>>> next(K) # Views are not iterators themselves

TypeError: dict_keys object is not an iterator

>>> for k in D.keys(): print(k, end=' ') # All iteration contexts use auto a c b

As for all iterators, you can always force a 3.0 dictionary view to build a real list by passing it to the list built-in. However, this usually isn't required except to display results interactively or to apply list operations like indexing:

>>> K = D.keys() >>> list(K) ['a', 'c', 'b']

<dict_values object at 0x026D8260> >>> list(V) [1, 3, 2]

>>> for (k, v) in D.items(): print(k, v, end=' ')

# Can still force a real list if needed

# Ditto for values() and items() views

In addition, 3.0 dictionaries still have iterators themselves, which return successive keys. Thus, it's not often necessary to call keys directly in this context:

{'a': 1, 'c': 3, 'b': 2} >>> I = iter(D) >>> next(I) 'a'

# Dictionaries still have own iterator

# Returns next key on each iteration

# Still no need to call keys() to iterate

# But keys is an iterator in 3.0 too!

Finally, remember again that because keys no longer returns a list, the traditional coding pattern for scanning a dictionary by sorted keys won't work in 3.0. Instead, convert keys views first with a list call, or use the sorted call on either a keys view or the dictionary itself, as follows:

>>> for k in sorted(D.keys())): print(k, D[k], end=' ')

>>> for k in sorted(D): print(k, D[k], end=

') # Best practice key sorting

Was this article helpful?

+1 0
Search Engine Manifesto

Search Engine Manifesto

Rank Your Web Pages HIGH in TOP Search Engine Popular Results For Maximum Exposure. Search Engines and How They Work Search Engines are special sites on the Web that are designed to help people find information stored on other sites.

Get My Free Ebook

Post a comment