A dictionary maps keys to values, like a phone’s contact list maps names to numbers. It is the right structure whenever you need to look something up by a name or ID rather than by position, and it does so very quickly.
What a dictionary is
Keys must be unique and hashable: strings, numbers, tuples of immutable items, frozensets. Lists, sets and dictionaries cannot be keys.
Values can be anything, including lists and other dictionaries.
Items are accessed by key, never by position: d[0] looks for the key 0.
Since Python 3.7, dictionaries remember the order in which keys were inserted.
Basic operations
Operation
Example
Effect
Create
d = {'one': 'uno', 'two': 'dos'} or dict()
Look up
d['two']
'dos'; KeyError if missing
Safe look-up
d.get('four', 'not found')
Default instead of an error
Add or change
d['three'] = 'tres'
Adds the key, or replaces its value
Delete
del d['one'] or d.pop('one')
KeyError if missing (unless pop has a default)
Test a key
'one' in d
Checks keys only, not values
Size
len(d)
Number of key–value pairs
Methods
Method
Purpose
keys(), values(), items()
Views of the keys, the values, and (key, value) pairs
get(key, default)
Value or default; never raises KeyError
update(other)
Add or overwrite pairs from another dictionary
pop(key[, default])
Remove a key and return its value
popitem()
Remove and return the last inserted pair
setdefault(key, default)
Return the value; if the key is missing, insert it with default first
fromkeys(keys, value)
New dictionary with the given keys, all set to value
copy(), clear()
Shallow copy; remove everything
Looping over a dictionary gives its keys: for k in d:; use for k, v in d.items(): to get both. sorted(d) returns a sorted list of keys. dict() builds a dictionary from pairs, for example dict([('jln', 1947), ('lbs', 1964)]).
Key takeaways
Dictionaries map unique hashable keys to any values, with average constant-time look-up.
They are mutable and keep insertion order; they cannot be indexed by position or sliced.
get, update, pop, items, keys and values are the core methods.
Iterating a dictionary yields its keys.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a dictionary that stores three students’ roll numbers (keys) and names (values), then show how to add a student, change a name, delete a student and print all entries.
Show worked answer
students = {101: "Geeta", 102: "Leena", 103: "Mahesh"}. Add: students[104] = "Amit". Change: students[103] = "Sham". Delete: del students[102] (or students.pop(102)). Print: for roll, name in students.items(): print(roll, name), which prints 101 Geeta, 103 Sham and 104 Amit in insertion order.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/data-structures-and-control-statements-in-python/dictionaries/ to read this page.