Online Book Reader

Home Category

Learning Python - Mark Lutz [132]

By Root 1951 0
only by key, not by position.

The built-in len function works on dictionaries, too; it returns the number of items stored in the dictionary or, equivalently, the length of its keys list. The dictionary in membership operator allows you to test for key existence, and the keys method returns all the keys in the dictionary. The latter of these can be useful for processing dictionaries sequentially, but you shouldn’t depend on the order of the keys list. Because the keys result can be used as a normal list, however, it can always be sorted if order matters (more on sorting and dictionaries later):

>>> len(D) # Number of entries in dictionary

3

>>> 'ham' in D # Key membership test alternative

True

>>> list(D.keys()) # Create a new list of my keys

['eggs', 'ham', 'spam']

Notice the second expression in this listing. As mentioned earlier, the in membership test used for strings and lists also works on dictionaries—it checks whether a key is stored in the dictionary. Technically, this works because dictionaries define iterators that step through their keys lists. Other types provide iterators that reflect their common uses; files, for example, have iterators that read line by line. We’ll discuss iterators in Chapters 14 and 20.

Also note the syntax of the last example in this listing. We have to enclose it in a list call in Python 3.0 for similar reasons—keys in 3.0 returns an iterator, instead of a physical list. The list call forces it to produce all its values at once so we can print them. In 2.6, keys builds and returns an actual list, so the list call isn’t needed to display results. More on this later in this chapter.

* * *

Note


The order of keys in a dictionary is arbitrary and can change from release to release, so don’t be alarmed if your dictionaries print in a different order than shown here. In fact, the order has changed for me too—I’m running all these examples with Python 3.0, but their keys had a different order in an earlier edition when displayed. You shouldn’t depend on dictionary key ordering, in either programs or books!

* * *

Changing Dictionaries In-Place

Let’s continue with our interactive session. Dictionaries, like lists, are mutable, so you can change, expand, and shrink them in-place without making new dictionaries: simply assign a value to a key to change or create an entry. The del statement works here, too; it deletes the entry associated with the key specified as an index. Notice also the nesting of a list inside a dictionary in this example (the value of the key 'ham'). All collection data types in Python can nest inside each other arbitrarily:

>>> D

{'eggs': 3, 'ham': 1, 'spam': 2}

>>> D['ham'] = ['grill', 'bake', 'fry'] # Change entry

>>> D

{'eggs': 3, 'ham': ['grill', 'bake', 'fry'], 'spam': 2}

>>> del D['eggs'] # Delete entry

>>> D

{'ham': ['grill', 'bake', 'fry'], 'spam': 2}

>>> D['brunch'] = 'Bacon' # Add new entry

>>> D

{'brunch': 'Bacon', 'ham': ['grill', 'bake', 'fry'], 'spam': 2}

As with lists, assigning to an existing index in a dictionary changes its associated value. Unlike with lists, however, whenever you assign a new dictionary key (one that hasn’t been assigned before) you create a new entry in the dictionary, as was done in the previous example for the key 'brunch'. This doesn’t work for lists because Python considers an offset beyond the end of a list out of bounds and throws an error. To expand a list, you need to use tools such as the append method or slice assignment instead.

More Dictionary Methods

Dictionary methods provide a variety of tools. For instance, the dictionary values and items methods return the dictionary’s values and (key,value) pair tuples, respectively (as with keys, wrap them in a list call in Python 3.0 to collect their values for display):

>>> D = {'spam': 2, 'ham': 1, 'eggs': 3}

>>> list(D.values())

[3, 1, 2]

>>> list(D.items())

[('eggs', 3), ('ham', 1), ('spam', 2)]

Such lists are useful in loops that need to step through dictionary entries one by one. Fetching a nonexistent key

Return Main Page Previous Page Next Page

®Online Book Reader