Python Dictionaries

Key-value pairs instead of positions. The four golden rules, nested dictionaries, and why membership and iteration both operate on keys only.

1. What is a Dictionary?

A dictionary stores data as key-value pairs: {key1: value1, key2: value2}. Each key maps to a value, and keys are used to look up values instead of positional indexes (unlike lists/strings).

Analogy: Just like a real-world language dictionary maps a word (key) to its meaning (value), a Python dictionary maps a unique identifier (key) to its data (value).
D = {"Name": "Nitish", "Gender": "Male"}
D
# {'Name': 'Nitish', 'Gender': 'Male'}

2. The 4 Golden Rules of Dictionaries

Mutable vs Immutable Types (recap)

TypeExamples
MutableList, Set, Dictionary
ImmutableString, Tuple, int, float, Boolean, complex
Why this matters: Since dictionary keys must be hashable (immutable), you can use strings, numbers, or tuples as keys โ€” but never a list.

3. Creating a Dictionary

A. Creating a 1-Dimensional (1D) Dictionary

D = {}                                   # empty dict
D = {"Name": "Nitish", "Gender": "Male"} # dict with data

student = {
    'name': 'Rahul',
    'college': 'XC'
}
print(student)

Using a list as a key โ†’ fails

D1 = {[1, 2, 3]: "Nitish"}
TypeError: unhashable type: 'list'

Why: Lists are mutable, so they can't be used as dictionary keys (keys must be hashable/immutable).

Using a tuple as a key โ†’ works

D1 = {(1, 2, 3): "Nitish"}
D1
# {(1, 2, 3): 'Nitish'}

Why: Tuples are immutable, so they are valid (hashable) keys.

Duplicate keys โ†’ last value wins

D2 = {"Name": "Rahul", "Name": "Rohit"}
D2
# {'Name': 'Rohit'}
โš ๏ธ Only one Name key survives โ€” the last assigned value overwrites earlier ones with the same key.

B. Creating a 2-Dimensional (Nested) Dictionary

A dictionary value can itself be another dictionary, letting you store complex structured data (e.g. a student profile with subject marks). You can extend this logic to build 3D or 4D dictionaries if needed.

D3 = {
    "Name": "Rohit",
    "College": "HIT",
    "Marks": {"M1": 56, "DS": 54, "Eng": 67}
}
D3
# {'Name': 'Rohit', 'College': 'HIT', 'Marks': {'M1': 56, 'DS': 54, 'Eng': 67}}

The outer dictionary holds three keys โ€” Name, College, and Marks โ€” and the value of Marks is itself a dictionary of subject keys mapped to integer marks.

4. Accessing Items from a Dictionary

Method 1: Square bracket notation D[key]

Because dictionaries have no numeric index, you access values by placing the key name inside square brackets.

D['Name']
# 'Nitish'

D[0]
# KeyError: 0   -> no indexing allowed (Rule 1), unless 0 is itself a defined key

Nested access

D3['Marks']['DS']
# 54

D3['Marks'] returns the inner dictionary {'M1': 56, 'DS': 54, 'Eng': 67}, and adding a second bracket ['DS'] accesses the key inside that inner dictionary.

Method 2: .get()

D.get('Name')
# 'Nitish'
Tutor's tip: .get() is safer than D['key'] since it won't raise a KeyError if the key doesn't exist (returns None instead, or a given default) โ€” but square bracket notation [] is preferred for nested (2D/3D) dictionaries, since chaining multiple .get() calls becomes cumbersome.

5. Editing and Adding Key-Value Pairs

A. Editing existing values

To change an existing value, assign a new value using its key.

D['Name'] = 'Rahul'          # 1D
D3['Marks']['DS'] = 64       # nested โ€” DS mark changes from 54 to 64

Python locates the existing key ('Name' or ['Marks']['DS']) and replaces its old value with the new one.

B. Adding new key-value pairs

To add a brand-new item, assign a value to a key that doesn't yet exist.

D['Age'] = 23                # 1D
D3['Marks']['M2'] = 50       # nested

Python checks whether the key exists; since it doesn't, Python creates the new key and binds the value to it.

Key takeaway: Assigning to a key that doesn't exist yet creates it; assigning to a key that already exists edits it โ€” same = syntax, different outcome depending on whether the key is present.

6. Deleting from a Dictionary

del on a variable โ€” removes the whole dictionary

del D5
D5
NameError: name 'D5' is not defined

del D completely deletes the dictionary variable from memory.

del on a key โ€” removes just that key-value pair

del D['Gender']
D
# {'Name': 'Rahul', 'Age': 23}

Using del with a specific key removes both the key and its associated value (this also works on nested dictionaries, e.g. del D3['Marks']['DS']).

.clear() โ€” empties the dictionary but keeps the variable

D.clear()
D
# {}

Unlike del, which removes the variable entirely, .clear() retains the dictionary object but empties all its contents.

Important Points

7. Dictionary Operations

Arithmetic operators are NOT supported

D1 + D2
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
D1 * 3
TypeError: unsupported operand type(s) for *: 'dict' and 'int'
Unlike lists/strings, dictionaries do not support + (concatenation) or * (repetition).

Membership check (in) โ€” checks keys only, not values

'Rohit' in D3
# False   -> 'Rohit' is a value, not a key

'Name' in D3
# True    -> 'Name' is a key

Membership checks on a dictionary operate exclusively on keys, never on values.

len(), min(), max(), sorted() โ€” all operate on keys

len(D3)          # 3   -> total number of key-value pairs
min(D3)           # alphabetically smallest key, e.g. 'College'
max(D3)           # alphabetically largest key, e.g. 'Name'
sorted(D3)        # ['College', 'Marks', 'Name']
sorted(D3, reverse=True)  # ['Name', 'Marks', 'College']

min/max work here because the keys are strings, which are comparable; sorted() returns keys as a sorted list.

.keys() and .values()

D3.keys()
# dict_keys(['Name', 'College', 'Marks'])

D3.values()
# dict_values(['Rohit', 'HIT', {'M1': 56, 'DS': 64, 'Eng': 67, 'M2': 50}])

8. Looping Through a Dictionary

By default, a for loop over a dictionary iterates over its keys.

for i in D3:
    print(i)
# Name
# College
# Marks

i takes the value of each top-level key during each iteration.

To get both key and value, index into the dict inside the loop:

for i in D3:
    print(i, D3[i])
# Name Rohit
# College HIT
# Marks {'M1': 56, 'DS': 64, 'Eng': 67, 'M2': 50}

D3[i] retrieves the value corresponding to key i.

9. Quick Reference Table

FunctionDescriptionExample
len(d)Number of key-value pairs (top-level keys)len(D3) โ†’ 3
min(d)Minimum key (lexicographic/alphabetical order)min(D3) โ†’ smallest key
max(d)Maximum key (lexicographic/alphabetical order)max(D3) โ†’ largest key
sorted(d)Sorted list of keyssorted(D3) โ†’ ['College', 'Marks', 'Name']

Things to Remember

Quick Revision Checklist

A dictionary ({key: value, ...}) is Python's mutable, unordered key-value collection. Keys must be immutable and unique; values can be anything, including nested dictionaries. Access/edit/add all use D['key']; safer read access uses .get(). Delete with del D['key'] (one item), del D (whole variable), or .clear() (empty it). No +/* support. in, min(), max(), sorted() all work against keys. Iterating a dict by default yields keys only โ€” pair with D[i] to get values too.