liveBook · Manning

Key

As explained in The Quick Python Book, Fourth Edition

A dictionary key is a hashable identifier used to access an associated value in a Python dictionary.

A dictionary key is a hashable identifier used to access an associated value. Unlike list indices, keys can be strings, numbers, tuples, or other eligible Python objects. section 7.1 section 7.4

Use dictionary keys according to these rules:

  • Assign and retrieve values with bracket notation, such as dictionary[key]. section 7.1
  • Choose immutable, hashable objects. Integers, floats, booleans, strings, bytes, frozensets, and suitable tuples can be keys. section 7.4
  • Do not use mutable objects such as lists, dictionaries, sets, or bytearrays as keys; tuples containing mutable objects are also invalid. section 7.4
  • Keys identify values rather than positions, so dictionary access does not depend on an item's numeric index. section 7.1 section 7.9

Words as keys

A word-counting loop uses each word as a key and updates its associated count: occurrences[word] = occurrences.get(word, 0) + 1. The resulting dictionary maps each distinct word to its frequency. section 7.3

Table 7.2 Python values eligible to be used as dictionary keys (view table figure)

Python type

Immutable?

Hashable?

Dictionary key?

int

Yes

Yes

Yes

float

Yes

Yes

Yes

boolean

Yes

Yes

Yes

complex

Yes

Yes

Yes

str

Yes

Yes

Yes

bytes

Yes

Yes

Yes

bytearray

No

No

No

list

No

No

No

tuple

Yes

Sometimes

Sometimes

set

No

No

No

frozenset

Yes

Yes

Yes

dictionary

No

No

No

Use the eligibility table to compare built-in types by immutability, hashability, and suitability as dictionary keys. section 7.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains key access, immutability, hashability, and tuple restrictions without developing dictionary implementation internals.
Examples
Demonstrates numeric and string keys, an English-to-French dictionary, and word-frequency counting.
What it assumes
Builds from list indexing and distinguishes dictionary keys from positional indices.
What you can do after
Apply keys to create, update, retrieve, and count dictionary values while avoiding unhashable key types.
How it connects
Connects keys with dictionaries, lists, hash tables, tuples, Counter, caching, and sparse matrices.

Also explained in

Compare how 10 books explain key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.