ЁЯТ╗
тМия╕П
ЁЯЦ▒я╕П
ЁЯЦея╕П
ЁЯТ╛
тЖР Back to Dashboard
Font Size:

1. Introduction

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.

2. Creating a Dictionary

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)])

3. Accessing Values

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

4. Adding and Updating Entries

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"})

5. Removing Entries

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'}
{}

6. Dictionary Methods and Functions

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

7. Traversing a Dictionary

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.

8. Nested Dictionaries

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

9. Dictionary in Practice

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)

10. Worked Examples with Explanation

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.

Quick Revision Tables

Table 1: Dictionary Methods

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)

Table 2: List vs Dictionary

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

Mind Map

graph TD A["Python Dictionary"] --> B["Creating"] A --> C["Accessing"] A --> D["Modifying"] A --> E["Traversal"] A --> F["Advanced"] B --> B1["{} key: value pairs"] B --> B2["dict() constructor"] C --> C1["dict[key]"] C --> C2["get(key, default)"] D --> D1["Add/update entries"] D --> D2["pop, popitem, del"] D --> D3["update, clear"] E --> E1["for key in dict"] E --> E2["items() loop"] F --> F1["Nested dictionaries"] F --> F2["Keys must be immutable"]

Important Diagrams (SVG)

Diagram 1: Structure of a Dictionary

Structure of a Dictionary student = {"name": "Aarav", "roll": 12} Keys (Immutable) "name" "roll" "marks" Values (Any type) "Aarav" 12 89 Golden Rule Dictionary keys must be immutable and unique; values can be of any data type

Diagram 2: Accessing a Dictionary with get()

dict[key] vs get(key) dict[key] Direct access by key Key exists -> value Key missing -> KeyError student["name"] Raises error for missing keys get(key) Safe access by key Key exists -> value Key missing -> None or default student.get("city") No error for missing keys Example student.get("city", "Not Available") -> "Not Available" student["city"] -> KeyError Golden Rule Use get(key, default) whenever the key may be missing to avoid KeyError

Common Mistakes

  1. Using a mutable type like a list as a dictionary key, which raises a TypeError because keys must be immutable.
  2. Accessing a missing key with dict[key] and getting a KeyError instead of using get().
  3. Confusing {} for an empty dictionary with set() for an empty set.
  4. Using duplicate keys; the later value overwrites the earlier one silently.
  5. Forgetting that dictionary order in older Python versions is not guaranteed; in Python 3.7+ insertion order is preserved.
  6. Trying to use sort() on a dictionary directly; dictionaries are not ordered lists and need sorted(d.items()) instead.
  7. Assuming popitem() removes a random pair; it removes the last inserted pair in modern Python.
  8. Confusing keys() and items(); the former gives only keys, the latter gives key-value tuples.

Exam Tips

  1. Memorise that keys must be immutable, so strings, numbers, and tuples are fine but lists are not.
  2. Practise the output of len(dict), dict.keys(), dict.values(), and dict.items().
  3. Remember get(key, default) is the safe way to access a possibly missing key.
  4. Be ready to write a program that counts the frequency of characters or words using a dictionary.
  5. Practise nested dictionary access such as students["s1"]["marks"].
  6. Know that del d[key] deletes an entry while clear() deletes all entries.

Conclusion

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.