A dictionary is an unordered collection of key-value pairs in Python. While a list stores values by their position, a dictionary stores values by a key, making lookups extremely fast and meaningful. Real-world data is almost always in the form of pairs: a roll number maps to a student's name, a word maps to its meaning, and a country maps to its capital. Dictionaries provide the perfect way to represent such relationships.
A dictionary is created by placing key-value pairs inside curly braces { }, separated by commas, with a colon : between each key and its value. The keys must be unique and must be of an immutable type such as string, number, or tuple, while values can be of any type, including lists and other dictionaries. Because dictionaries are mutable, we can add, update, and delete entries as the program runs.
This chapter explains how to create and access dictionaries, how to add and update entries, how to remove entries, and how to traverse a dictionary with loops. We will study all the important methods such as keys(), values(), items(), get(), update(), pop(), and clear(). We will also see nested dictionaries and how dictionaries and lists are often combined to represent tabular data. Dictionary questions are extremely common in exams because they test both conceptual understanding and practical programming skill.
A dictionary is created using curly braces with key-value pairs.
student = {"name": "Aarav", "roll": 12, "marks": 89}
print(student)
Output:
{'name': 'Aarav', 'roll': 12, 'marks': 89}
An empty dictionary is created with {} or with the dict() constructor:
d1 = {}
d2 = dict()
The dict() constructor can also build a dictionary from a list of pairs:
d = dict([("a", 1), ("b", 2)])
A value is accessed using its key inside square brackets. If the key does not exist, a KeyError is raised.
student = {"name": "Aarav", "roll": 12, "marks": 89}
print(student["name"])
print(student["marks"])
Output:
Aarav
89
To avoid a KeyError, the get() method can be used. It returns None (or a default value) if the key is missing:
print(student.get("city"))
print(student.get("city", "Not Available"))
Output:
None
Not Available
To add a new key-value pair, simply assign a value to a new key. To update, assign to an existing key.
student = {"name": "Aarav", "roll": 12}
student["marks"] = 89
student["name"] = "Aarav Kumar"
print(student)
Output:
{'name': 'Aarav Kumar', 'roll': 12, 'marks': 89}
The update() method adds multiple key-value pairs at once:
student.update({"class": "XI", "section": "A"})
pop(key): Removes the entry with the given key and returns its value.popitem(): Removes and returns the last inserted key-value pair (as a tuple).del dict[key]: Deletes the entry with the given key.clear(): Removes all entries from the dictionary.student = {"name": "Aarav", "roll": 12, "marks": 89}
value = student.pop("marks")
print(value)
print(student)
del student["roll"]
print(student)
student.clear()
print(student)
Output:
89
{'name': 'Aarav'}
{'name': 'Aarav'}
{}
keys(): Returns a view of all keys.values(): Returns a view of all values.items(): Returns a view of all key-value pairs as tuples.get(key, default): Returns the value for the key or the default.update(dict): Updates with key-value pairs from another dictionary.pop(key): Removes the key and returns its value.len(dict): Returns the number of key-value pairs.student = {"name": "Aarav", "roll": 12, "marks": 89}
print(student.keys())
print(student.values())
print(student.items())
print(len(student))
Output:
dict_keys(['name', 'roll', 'marks'])
dict_values(['Aarav', 12, 89])
dict_items([('name', 'Aarav'), ('roll', 12), ('marks', 89)])
3
We can loop over keys, values, or both.
student = {"name": "Aarav", "roll": 12, "marks": 89}
for key in student:
print(key, "->", student[key])
for key, value in student.items():
print(key, value)
Both snippets print each key with its corresponding value, one pair per line.
Values in a dictionary can themselves be dictionaries, creating a nested structure that is very useful for representing complex data.
students = {
"s1": {"name": "Aarav", "marks": 89},
"s2": {"name": "Bina", "marks": 94}
}
print(students["s1"]["name"])
print(students["s2"]["marks"])
Output:
Aarav
94
Dictionaries are commonly used to store and retrieve data quickly. For example, a word-frequency counter or a phone book are naturally represented as dictionaries. They pair beautifully with lists: a list of dictionaries can represent a database table, and a dictionary of lists can group data by category.
phonebook = {"Amit": 98765, "Bina": 12345, "Chirag": 55555}
for name, number in phonebook.items():
print(name, number)
Counting the frequency of characters. Suppose we wish to count how many times each character appears in the string "mangoes". We start with an empty dictionary and loop over every character. For each character, we check whether it already exists as a key. If it does, we increase its count by one; otherwise we create the key with an initial value of 1. This program, which uses the in operator to test the presence of a key and the assignment operator to update values, is a classic demonstration of how dictionaries turn a counting problem into a few lines of code. The same idea works for counting the words in a sentence, splitting the sentence first with the split() method and then applying the identical counting loop to the resulting list.
Building a phone book. A phone book is the most natural example of a dictionary because each name maps to exactly one number. Adding a new contact is as simple as assigning a value to a new key, and updating an existing number is the same operation carried out on an existing key. Deleting a contact uses pop() or del. Searching for a number by name is a single lookup that does not require scanning the whole collection, unlike a list, where you would have to check each element in order. This speed of lookup is the fundamental advantage of a dictionary over a list for paired data, and it is why dictionaries power so many real-world systems such as search indexes, configuration stores, and caches.
Combining lists and dictionaries. A list of dictionaries is an excellent way to store records such as the marks of several students. Each dictionary holds the details of one student, and the outer list holds the whole class. Using a loop over the list, we can compute the total marks, the average, the highest scorer, or the names of students who scored above a threshold. This pattern, where one data structure is nested inside another, is used throughout real programs and appears frequently in examination questions, so practising it with nested loops and conditional checks is highly recommended.
| Method | Action | Example |
|---|---|---|
| keys() | All keys | d.keys() |
| values() | All values | d.values() |
| items() | All key-value pairs | d.items() |
| get(k) | Value of k, or None | d.get("a") |
| update(d) | Add multiple pairs | d.update({"b": 2}) |
| pop(k) | Remove k, return value | d.pop("a") |
| clear() | Remove all entries | d.clear() |
| len(d) | Number of pairs | len(d) |
| Feature | List | Dictionary |
|---|---|---|
| Delimiter | Square brackets [] |
Curly braces {} |
| Access by | Index (position) | Key |
| Key requirement | None | Unique, immutable keys |
| Ordered | Yes (ordered by index) | Insertion ordered |
| Duplicates allowed | Yes | Keys no, values yes |
| Mutable | Yes | Yes |
dict[key] and getting a KeyError instead of using get().{} for an empty dictionary with set() for an empty set.sort() on a dictionary directly; dictionaries are not ordered lists and need sorted(d.items()) instead.popitem() removes a random pair; it removes the last inserted pair in modern Python.keys() and items(); the former gives only keys, the latter gives key-value tuples.len(dict), dict.keys(), dict.values(), and dict.items().get(key, default) is the safe way to access a possibly missing key.students["s1"]["marks"].del d[key] deletes an entry while clear() deletes all entries.Dictionaries bring a new dimension to Python programming by storing data as meaningful key-value pairs instead of positional values. They allow instant lookups, flexible modification, and natural representation of real-world relationships such as phone books, word counts, and student records. The safety offered by get(), the convenience of keys(), values(), and items(), and the power of nesting make dictionaries indispensable. Combined with lists, they can represent almost any data structure needed in school projects. Mastering dictionaries completes the core data-structure toolkit needed for data visualisation and database programming in the following chapters.