A map connects one object to another so you can look up the second object using the first. In Python, this data structure is a dictionary, or dict. Each entry has a key, which you look up, and a value, which you get back. Think of a grocery item mapped to the quantity you need. section 27.0 section 27.1
Make and use a grocery map
grocery = {"milk": 1, "eggs": 12, "bread": 2} print(grocery["eggs"]) grocery["milk"] = 2 The braces create a dictionary. Commas separate its entries; in each entry, the key sits left of the colon and its value sits right. Looking up "eggs" gets 12. Assigning a value to the existing key "milk" replaces its old value. section 27.1 section 27.2
Choose a dictionary when you have pairs to connect, then use these operations as you need them:
- Start with {} and add an entry with d[key] = value. len(d) tells you how many entries there are. section 27.1 section 27.2
- Use d.pop(key) to remove an entry and get its value back. section 27.3
- Loop over d.keys() to visit keys and look up their values; d.values() gives you the values directly. section 27.4
A list connects integer positions to items; a dictionary lets you choose keys suited to the pairs you have. Dictionaries can change, but each key must be unique and immutable. Values may be mutable, such as lists of quiz grades. Do not use printed entry order as a substitute for keys: the Python 3.5 examples can display entries in a different order from insertion. section 27.0 section 27.2 section 27.4 section 27.6
Try this: how would you map each song name to its rating, then print only the songs rated 5? The same key–value idea can count words: use each word as a key and increase its count each time it appears. Those counts can also help compare two documents. section 27.6 section 27.5 section 29.0









































