Skip to content
Course contents
The core of the language

Looking things up by name

A dictionary maps a key to a value, a ticker to its price, a name to a number, so you can look things up by name rather than position. It is how you model labelled data before pandas arrives.

7 min readChapter 8 of 30
What you will learn
  • Create a dictionary and read and write its values
  • Iterate over keys and values
  • Model a simple symbol-to-price mapping

A list is organised by position, which is perfect for a run of prices but awkward when you want to find a value by name. If you have the prices of several stocks, you do not want Reliance's price to be "the one at index 3"; you want to ask for it by its ticker. Python's tool for that is the dictionary, which maps a key, like a ticker, to a value, like a price. It is how you hold labelled data before the specialised table tools arrive later in the course.

Keys and values

A dictionary maps a key to a value, so you look things up by name rather than position: prices['TCS'] returns its price.
A dictionary maps a key to a value, so you look things up by name rather than position: prices['TCS'] returns its price.

You create a dictionary with curly braces, listing each key and its value separated by a colon. You then read a value by its key, the way you would look a word up in a dictionary. This program maps tickers to prices and works with them.

ExampleCreating, reading, updating, and safely querying a dictionarych08/dictionaries.py
# A dictionary maps a key to a value: here, a symbol to its price.
prices = {
    "RELIANCE": 1402.5,
    "TCS": 3120.0,
    "INFY": 1560.0,
}

print("TCS price:", prices["TCS"])     # look up by key
prices["HDFCBANK"] = 1675.0            # add a new entry
prices["INFY"] = 1555.0                # update an existing one
print("Symbols:", list(prices.keys()))
print("How many:", len(prices))
print("Missing symbol:", prices.get("WIPRO", "not tracked"))
Output
TCS price: 3120.0
Symbols: ['RELIANCE', 'TCS', 'INFY', 'HDFCBANK']
How many: 4
Missing symbol: not tracked

The output shows the pieces. prices["TCS"] looks up TCS by name and returns 3120.0. Assigning to a new key, prices["HDFCBANK"] = 1675.0, adds an entry, while assigning to an existing key, prices["INFY"] = 1555.0, updates it in place rather than adding a duplicate, which is why the list of keys that follows has four names, not five, and len(prices) is 4. The keys come back in the order they were added.

Asking safely

The last line introduces a genuinely useful habit. If you look up a key that does not exist with the square-bracket form, Python raises a KeyError and stops, which you met as a problem earlier. The .get method avoids that: prices.get("WIPRO", "not tracked") returns the value if the key exists and the fallback you supplied, "not tracked", if it does not, so the program continues calmly instead of crashing. When you work with real data where a symbol might be missing, reaching for .get with a sensible default is how you keep a program from falling over on the one row that is incomplete.

The dictionary is the right mental model for a lot of market data: a symbol to its price, a date to a close, a setting to its value. You can also walk through everything in a dictionary, its keys, its values, or both together, which pairs naturally with the loops of the next chapter but one. For now, hold the core idea: a dictionary looks things up by a meaningful key rather than a bare position, and that is exactly what you want when the label matters.

What to carry forward

A dictionary maps keys to values, letting you look things up by name, a ticker to its price, a date to a close, rather than by position. You read and write with square brackets, where assigning to a new key adds and to an existing key updates, and you query safely with .get and a default to avoid a KeyError. It is the natural model for labelled market data before the table tools arrive.

So far programs run straight through, doing the same thing every time. To react to data, a program has to make decisions. The next chapter introduces conditionals, the if statements that let code choose.