Python Dictionaries
Python · Dictionaries
Theory
A dictionary (dict) stores key-value pairs: employee = {'name': 'Asha', 'salary': 65000}. You look a value up by its key, employee['salary'] gives 65000, instead of by position. Assigning to a key either updates it, if it exists, or adds a new pair: employee['dept'] = 'IT'. Reading a key that does not exist with square brackets raises KeyError, which is why .get() exists. Keys are unique; assigning the same key again simply overwrites the old value.
A dict is a hash table. Python hashes the key to find the slot where its value lives, so lookups, inserts and deletes take roughly constant time on average (O(1)) even with millions of entries. That is why keys must be hashable (str, int, tuple), while values can be anything, including lists and other dicts. Since Python 3.7, dicts keep their insertion order, so looping returns keys in the order you added them. key in employee checks keys, not values.
Why we use it
Most real-world records are naturally 'field: value': a customer, a config, a JSON response. A dict lets you reach any field instantly by name, and it is the go-to structure for lookups, counting and grouping.
When to use it
Use a dict whenever you look things up by a label: ID to record, word to count, code to description. Use a list when position is what matters. For counting use collections.Counter; for default values on missing keys use collections.defaultdict.
How it works
- Evaluate employee['salary']
- Compute hash('salary') to find the slot
- Is the key 'salary' stored there? Yes: Return its value, 65000. No: Raise KeyError: 'salary'.
- Assignment employee['dept'] = 'IT' hashes 'dept' the same way
- Does 'dept' already exist? Yes: Overwrite its value. No: Add a new pair at the end.
- print(employee['salary']) shows 65000
Syntax
my_dict = {"key": "value"}Example
employee = {'name': 'Asha', 'salary': 65000}
employee['salary']Key points
- Keys must be unique and immutable (hashable)
- Insertion order is preserved since Python 3.7
- Lookup by key is average O(1), no matter how big the dict
- d[key] on a missing key raises KeyError; use d.get(key) to avoid it
- key in d checks keys, not values
- Values can be anything, including lists and other dicts