Online Book Reader

Home Category

Learning Python - Mark Lutz [137]

By Root 1581 0
are also useful for initializing dictionaries from keys lists, in much the same way as the fromkeys method we met at the end of the preceding section:

>>> D = dict.fromkeys(['a', 'b', 'c'], 0) # Initialize dict from keys

>>> D

{'a': 0, 'c': 0, 'b': 0}

>>> D = {k:0 for k in ['a', 'b', 'c']} # Same, but with a comprehension

>>> D

{'a': 0, 'c': 0, 'b': 0}

>>> D = dict.fromkeys('spam') # Other iterators, default value

>>> D

{'a': None, 'p': None, 's': None, 'm': None}

>>> D = {k: None for k in 'spam'}

>>> D

{'a': None, 'p': None, 's': None, 'm': None}

Like related tools, dictionary comprehensions support additional syntax not shown here, including nested loops and if clauses. Unfortunately, to truly understand dictionary comprehensions, we need to also know more about iteration statements and concepts in Python, and we don’t yet have enough information to address that story well. We’ll learn much more about all flavors of comprehensions (list, set, and dictionary) in Chapters 14 and 20, so we’ll defer further details until later. We’ll also study the zip built-in we used in this section in more detail in Chapter 13, when we explore for loops.

Dictionary views

In 3.0 the dictionary keys, values, and items methods all return view objects, whereas in 2.6 they return actual result lists. View objects are iterables, which simply means objects that generate result items one at a time, instead of producing the result list all at once in memory. Besides being iterable, dictionary views also retain the original order of dictionary components, reflect future changes to the dictionary, and may support set operations. On the other hand, they are not lists, and they do not support operations like indexing or the list sort method; nor do they display their items when printed.

We’ll discuss the notion of iterables more formally in Chapter 14, but for our purposes here it’s enough to know that we have to run the results of these three methods through the list built-in if we want to apply list operations or display their values:

>>> D = dict(a=1, b=2, c=3)

>>> D

{'a': 1, 'c': 3, 'b': 2}

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

>>> K

>>> list(K) # Force a real list in 3.0 if needed

['a', 'c', 'b']

>>> V = D.values() # Ditto for values and items views

>>> V

>>> list(V)

[1, 3, 2]

>>> list(D.items())

[('a', 1), ('c', 3), ('b', 2)]

>>> K[0] # List operations fail unless converted

TypeError: 'dict_keys' object does not support indexing

>>> list(K)[0]

'a'

Apart from when displaying results at the interactive prompt, you will probably rarely even notice this change, because looping constructs in Python automatically force iterable objects to produce one result on each iteration:

>>> for k in D.keys(): print(k) # Iterators used automatically in loops

...

a

c

b

In addition, 3.0 dictionaries still have iterators themselves, which return successive keys—as in 2.6, it’s still often not necessary to call keys directly:

>>> for key in D: print(key) # Still no need to call keys() to iterate

...

a

c

b

Unlike 2.X’s list results, though, dictionary views in 3.0 are not carved in stone when created—they dynamically reflect future changes made to the dictionary after the view object has been created:

>>> D = {'a':1, 'b':2, 'c':3}

>>> D

{'a': 1, 'c': 3, 'b': 2}

>>> K = D.keys()

>>> V = D.values()

>>> list(K) # Views maintain same order as dictionary

['a', 'c', 'b']

>>> list(V)

[1, 3, 2]

>>> del D['b'] # Change the dictionary in-place

>>> D

{'a': 1, 'c': 3}

>>> list(K) # Reflected in any current view objects

['a', 'c']

>>> list(V) # Not true in 2.X!

[1, 3]

Dictionary views and sets

Also unlike 2.X’s list results, 3.0’s view objects returned by the keys method are set-like and support common set operations such as intersection and union; values views are not, since they aren’t unique, but items results are if their (key, value) pairs are unique and hashable. Given that sets

Return Main Page Previous Page Next Page

®Online Book Reader