Key-value pairs instead of positions. The four golden rules, nested dictionaries, and why membership and iteration both operate on keys only.
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'}
D[0] or D[-1] fail). Access is done strictly via keys.| Type | Examples |
|---|---|
| Mutable | List, Set, Dictionary |
| Immutable | String, 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.
D = {} # empty dict
D = {"Name": "Nitish", "Gender": "Male"} # dict with data
student = {
'name': 'Rahul',
'college': 'XC'
}
print(student)
{} contain the key-value pairs.'name' is a key associated with the string value 'Rahul'; 'college' is a key associated with 'XC'.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).
D1 = {(1, 2, 3): "Nitish"}
D1
# {(1, 2, 3): 'Nitish'}
Why: Tuples are immutable, so they are valid (hashable) keys.
D2 = {"Name": "Rahul", "Name": "Rohit"}
D2
# {'Name': 'Rohit'}
Name key survives โ the last assigned value overwrites earlier ones with the same key.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.
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
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.
D.get('Name')
# 'Nitish'
Tutor's tip:.get()is safer thanD['key']since it won't raise aKeyErrorif the key doesn't exist (returnsNoneinstead, or a given default) โ but square bracket notation[]is preferred for nested (2D/3D) dictionaries, since chaining multiple.get()calls becomes cumbersome.
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.
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.
del D5
D5
NameError: name 'D5' is not defined
del D completely deletes the dictionary variable from memory.
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']).
D.clear()
D
# {}
Unlike del, which removes the variable entirely, .clear() retains the dictionary object but empties all its contents.
Important Points
del D โ deletes the variable itself (it no longer exists).del D['key'] โ deletes only that key-value pair.D.clear() โ keeps D as a dictionary object, but empties all its contents ({}).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).
'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(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.
D3.keys()
# dict_keys(['Name', 'College', 'Marks'])
D3.values()
# dict_values(['Rohit', 'HIT', {'M1': 56, 'DS': 64, 'Eng': 67, 'M2': 50}])
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.
| Function | Description | Example |
|---|---|---|
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 keys | sorted(D3) โ ['College', 'Marks', 'Name'] |
D['key'] = value both adds (if key is new) and edits (if key exists)..get('key') is a safer alternative to D['key'] for lookups; [] is preferred for nested dicts.del D['key'] removes one pair; del D removes the variable; D.clear() empties the dict.+ and * are not supported on dictionaries.in checks keys only, not values.min(), max(), sorted(), len() all operate on keys.for i in D gives keys; use D[i] inside the loop to also get values.{key: value} pairs.D[key]).for loops and the in operator both operate on keys only.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.