A dictionary maps each unique key to a value. Use it when a program needs to associate one piece of information with another, such as a digit with its substitute, a letter with a line of text, or a CSV field name with its value. section 4.0 section 4.1
Create, inspect, and query dictionaries with these core operations:
- Create an empty dictionary with {} or dict(), then add entries with square brackets: answers['name'] = 'Sir Lancelot'. section 4.1.1
- Retrieve a value with dictionary[key]. A missing key raises KeyError; dictionary.get(key) returns None or a supplied fallback instead. section 4.1.2
- Check membership with key in dictionary, count pairs with len(), and inspect keys(), values(), or items(). section 4.1.2 section 4.1.3
- Iterate through items() to unpack each key and value; assigning an existing key again replaces its previous value. section 4.1.3
- Use strings or immutable values as keys, and choose readable lowercase names with underscores for dictionary keys. section 4.1.1 section 4.1.3
Encode characters with a lookup dictionary
Store text representations of digits as both keys and values, then process an input string one character at a time. The fallback preserves nondigit characters unchanged. jumper = {'1': '9', '2': '8', '3': '7', '4': '6', '5': '0', '6': '4', '7': '3', '8': '2', '9': '1', '0': '5'} encoded = '' for char in 'Call 1-800 today!': encoded += jumper.get(char, char) print(encoded) # Call 9-255 today! The same lookup pattern can index file lines: use each line's first, uppercased character as a key and the cleaned line as its value. section 4.2 section 4.4.2 section 7.3.2
| A Python dictionary allows us to relate some thing (a “key”) to some other thing (a “value”). An actual dictionary does this. If we look up a word like “quirky” in a dictionary (www.merriam-webster.com/dictionary/ quirky), we can find a definition, as in figure 4.1. We can think of the word itself as the “key” and the definition as the “value.” |
![]() |
A word and its definition provide a compact mental model for a dictionary: the word is the key, and the definition is the value. section 4.1










































