liveBook · Manning

Key

As explained in Get Programming: Learn to code with Python

An immutable object used to identify and retrieve a corresponding value in a dictionary.

A key is the object used to look up a corresponding value in a Python dictionary. Each dictionary entry is a key-value pair: the key appears before the colon, and its value appears after it. For example, a grocery dictionary can use item names as keys and quantities as values. section 27.1

Keep these key rules in mind:

  • Keys must be immutable objects, so their contents cannot change while the dictionary uses them. section 27.2
  • Every key must be unique. Assigning a new value to an existing key overwrites the previous value instead of creating another entry. section 27.2
  • Values may be mutable or immutable, and a value can contain several objects inside one tuple or list. section 27.1 section 27.6
  • A key can retrieve its value directly, or you can inspect all keys with keys() and loop through them. section 27.4

Grocery quantities

grocery = {"milk": 1, "eggs": 12, "bread": 2} print(grocery["eggs"]) Here, "eggs" is the key, and 12 is its value. The square brackets ask the dictionary to retrieve the value associated with that key. Replacing it with grocery["eggs"] = 18 changes the existing entry. section 27.1 section 27.2

grocery = {"milk": 1, "eggs": 12, "bread": 2}

View the compact dictionary example showing keys on the left of each colon and their corresponding values on the right. section 27.1

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains key-value syntax, uniqueness, immutability, and a brief hash-function rationale without developing dictionary internals.
Examples
Uses grocery items, animal legs, song ratings, student grades, and city populations as dictionary keys.
What you can do after
Apply it via Python dictionaries to create entries, retrieve values, update mappings, and iterate over keys.
How it connects
Connects keys to dictionaries, values, hash functions, tuples, lists, and mutability.

Also explained in

Compare how 10 books explain key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.