12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Later in this chapter and book, you’ll learn about two alternative ways to builddictionaries, demonstrated at the end of Table 8-2: you can pass zipped lists of key/value tuples or keyword function arguments to the new dict call (really, a typeconstructor). We’ll explore keyword arguments in Chapter 16. We’ll also discuss thezip function in Chapter 13; it’s a way to construct a dictionary from key and valuelists in a single call. If you cannot predict the set of keys and values in your code, forinstance, you can always build them up as lists and zip them together dynamically.Changing Dictionaries In-PlaceLet’s continue with our interactive session. Dictionaries, like lists, are mutable, soyou 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 workshere, too; it deletes the entry associated with the key specified as an index. Noticealso the nesting of a list inside a dictionary in this example (the value of the key'ham'). All collection data types in <strong>Python</strong> can nest inside each other arbitrarily:>>> d2['ham'] = ['grill', 'bake', 'fry'] # Change entry>>> d2{'eggs': 3, 'spam': 2, 'ham': ['grill', 'bake', 'fry']}>>> del d2['eggs'] # Delete entry>>> d2{'spam': 2, 'ham': ['grill', 'bake', 'fry']}>>> d2['brunch'] = 'Bacon' # Add new entry>>> d2{'brunch': 'Bacon', 'spam': 2, 'ham': ['grill', 'bake', 'fry']}As with lists, assigning to an existing index in a dictionary changes its associatedvalue. Unlike with lists, however, whenever you assign a new dictionary key (one thathasn’t been assigned before), you create a new entry in the dictionary, as was done inthe previous example for the key 'brunch.' This doesn’t work for lists because<strong>Python</strong> considers an offset beyond the end of a list out of bounds and throws anerror. To expand a list, you need to use tools such as the append method or sliceassignment instead.More Dictionary MethodsDictionary methods provide a variety of tools. For instance, the dictionary valuesand items methods return lists of the dictionary’s values and (key,value) pair tuples,respectively:>>> d2 = {'spam': 2, 'ham': 1, 'eggs': 3}>>> d2.values( )[3, 1, 2]>>> d2.items( )[('eggs', 3), ('ham', 1), ('spam', 2)]Dictionaries in Action | 163

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!