Python Programming for Beginners

Chapter 10: Python Dictionaries – Creating, Accessing, Updating and Using Key-Value Pairs

Chapter 10: Python Dictionaries – Creating, Accessing, Updating and Using Key-Value Pairs

10.1 Introduction

In the previous chapter, we learned about Sets, which are useful for storing unique values.

In this chapter, we will learn about one of Python's most useful data structures: the Dictionary.

A dictionary stores data in key-value pairs.

For example:

 

student = {    "name": "Aman",    "age": 15,    "marks": 85 }

 

Here:

  • "name" is a key.
  • "Aman" is its value.
  • "age" is a key.
  • 15 is its value.
  • "marks" is a key.
  • 85 is its value.

Dictionaries are widely used in real-world Python programs because they make it easy to organize and retrieve related information.

10.2 What is a Dictionary?

A dictionary is a collection of key-value pairs.

Basic syntax:

 

dictionary_name = {    "key1": "value1",    "key2": "value2" }

 

Example:

 

student = {    "name": "Aman",    "class": 10,    "marks": 88 } print(student)

 

Output:

{'name': 'Aman', 'class': 10, 'marks': 88}

 

10.3 Key-Value Pairs

Each item in a dictionary consists of a key and a value.

Example:

 

student = {    "name": "Aman",    "age": 16 }

 

The structure is:

"name" → "Aman" "age"  → 16

 

The key is used to find its corresponding value.

10.4 Creating a Dictionary

Example:

 

person = {    "name": "Ravi",    "age": 20,    "city": "Bhopal" } print(person)

 

A dictionary can contain different types of values.

10.5 Empty Dictionary

An empty dictionary can be created using {}.

 

data = {} print(data)

 

Output:

{}

 

You can also use:

 

data = dict() print(data)

 

10.6 Accessing Dictionary Values

You can access a value using its key.

 

student = {    "name": "Aman",    "marks": 85 } print(student["name"]) print(student["marks"])

 

Output:

Aman 85

 

Unlike lists and tuples, dictionaries are generally accessed using keys rather than numeric indexes.

10.7 Using the get() Method

Another way to access a dictionary value is the get() method.

 

student = {    "name": "Aman",    "marks": 85 } print(student.get("name"))

 

Output:

Aman

 

10.8 Difference Between [] and get()

Suppose the key does not exist.

Using brackets:

 

student = {    "name": "Aman" } print(student["age"])

 

This raises a KeyError.

Using get():

 

print(student.get("age"))

 

The result is:

None

 

You can also provide a default value:

 

print(student.get("age", "Not available"))

 

Output:

Not available

 

This makes get() useful when a key may not exist.

10.9 Adding a New Key-Value Pair

You can add a new item by assigning a value to a new key.

 

student = {    "name": "Aman",    "age": 16 } student["city"] = "Bhopal" print(student)

 

Output:

{'name': 'Aman', 'age': 16, 'city': 'Bhopal'}

 

10.10 Updating an Existing Value

If the key already exists, assigning a new value changes the existing value.

 

student = {    "name": "Aman",    "marks": 80 } student["marks"] = 90 print(student)

 

Output:

{'name': 'Aman', 'marks': 90}

 

10.11 Updating Multiple Values

The update() method can update multiple key-value pairs.

 

student = {    "name": "Aman",    "age": 16,    "marks": 80 } student.update({    "age": 17,    "marks": 90 }) print(student)

 

The existing values are updated.

10.12 Adding Multiple Values with update()

update() can also add new keys.

 

student = {    "name": "Aman" } student.update({    "age": 16,    "city": "Bhopal" }) print(student)

 

10.13 Removing an Item with pop()

The pop() method removes a key and returns its value.

 

student = {    "name": "Aman",    "age": 16,    "marks": 85 } removed = student.pop("age") print("Removed:", removed) print(student)

 

Output:

Removed: 16 {'name': 'Aman', 'marks': 85}

 

10.14 Removing the Last Inserted Item with popitem()

The popitem() method removes and returns the last inserted key-value pair.

 

student = {    "name": "Aman",    "age": 16,    "marks": 85 } item = student.popitem() print(item) print(student)

 

Output:

('marks', 85)

 

The remaining dictionary contains the earlier entries.

10.15 Using del

The del statement can remove a specific key.

 

student = {    "name": "Aman",    "age": 16,    "marks": 85 } del student["age"] print(student)

 

10.16 Clearing a Dictionary

The clear() method removes all items.

 

student = {    "name": "Aman",    "age": 16 } student.clear() print(student)

 

Output:

{}

 

10.17 Checking Whether a Key Exists

Use the in operator.

 

student = {    "name": "Aman",    "age": 16 } if "name" in student:    print("Name is available")

 

Output:

Name is available

 

You can also check:

 

if "marks" not in student:    print("Marks are not available")

 

10.18 Finding the Number of Items

Use len().

 

student = {    "name": "Aman",    "age": 16,    "marks": 85 } print(len(student))

 

Output:

3

 

10.19 Dictionary Keys

Dictionary keys must be hashable.

Common examples include:

  • Strings
  • Integers
  • Floats
  • Tuples containing hashable values

Example:

 

data = {    1: "One",    2: "Two",    3: "Three" } print(data[1])

 

Output:

One

 

Strings are the most common type of dictionary key.

10.20 Dictionary Values

Dictionary values can be of many types.

 

student = {    "name": "Aman",    "age": 16,    "marks": 88.5,    "passed": True }

 

Values can also be lists, tuples, sets, or even other dictionaries.

10.21 Dictionary with a List as a Value

 

student = {    "name": "Aman",    "subjects": ["Maths", "Science", "English"] } print(student["subjects"])

 

Output:

['Maths', 'Science', 'English']

 

You can access an individual list item:

 

print(student["subjects"][0])

 

Output:

Maths

 

10.22 Dictionary with a Tuple as a Value

 

location = {    "name": "School",    "coordinates": (23.25, 77.41) } print(location["coordinates"])

 

10.23 Dictionary with Another Dictionary

A dictionary can contain another dictionary. This is called a nested dictionary.

 

students = {    "student1": {        "name": "Aman",        "marks": 85    },    "student2": {        "name": "Ravi",        "marks": 90    } } print(students)

 

10.24 Accessing Nested Dictionary Values

 

print(students["student1"]["name"])

 

Output:

Aman

 

And:

 

print(students["student2"]["marks"])

 

Output:

90

 

10.25 Looping Through a Dictionary

A for loop can be used to iterate through a dictionary.

 

student = {    "name": "Aman",    "age": 16,    "marks": 85 } for key in student:    print(key)

 

Output:

name age marks

 

This loops through the keys.

10.26 Looping Through Dictionary Keys

You can explicitly use the keys() method.

 

student = {    "name": "Aman",    "age": 16,    "marks": 85 } for key in student.keys():    print(key)

 

10.27 Getting All Values

Use the values() method.

 

student = {    "name": "Aman",    "age": 16,    "marks": 85 } for value in student.values():    print(value)

 

Output:

Aman 16 85

 

10.28 Getting Keys and Values

The items() method returns key-value pairs.

 

student = {    "name": "Aman",    "age": 16,    "marks": 85 } for key, value in student.items():    print(key, ":", value)

 

Output:

name : Aman age : 16 marks : 85

 

This is one of the most useful ways to loop through a dictionary.

10.29 keys(), values() and items()

MethodPurpose
keys()Returns dictionary keys
values()Returns dictionary values
items()Returns key-value pairs

Example:

 

student.keys() student.values() student.items()

 

10.30 Copying a Dictionary

You can create a copy using the copy() method.

 

student = {    "name": "Aman",    "marks": 85 } student_copy = student.copy() print(student_copy)

 

This creates a separate dictionary object.

10.31 Why Use copy()?

Consider:

 

student = {    "name": "Aman" } student_copy = student

 

Both variables refer to the same dictionary object.

Changing one can affect the other.

Using:

 

student_copy = student.copy()

 

creates a separate shallow copy.

10.32 Dictionary Comprehension

Python supports dictionary comprehension.

Example:

 

numbers = [1, 2, 3, 4, 5] squares = {number: number ** 2 for number in numbers} print(squares)

 

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

 

The general syntax is:

 

{key: value for item in iterable}

 

10.33 Dictionary Comprehension with a Condition

 

numbers = range(1, 11) even_squares = {    number: number ** 2    for number in numbers    if number % 2 == 0 } print(even_squares)

 

Output:

{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

 

10.34 Creating a Dictionary with dict()

A dictionary can also be created using dict().

 

student = dict(    name="Aman",    age=16,    marks=85 ) print(student)

 

Output:

{'name': 'Aman', 'age': 16, 'marks': 85}

 

This syntax is convenient when the keys are valid Python identifiers.

10.35 Dictionary from Two Lists

You can use zip() with dict() to create a dictionary.

 

keys = ["name", "age", "city"] values = ["Aman", 16, "Bhopal"] student = dict(zip(keys, values)) print(student)

 

Output:

{'name': 'Aman', 'age': 16, 'city': 'Bhopal'}

 

10.36 Dictionary with Numeric Keys

Dictionary keys do not have to be strings.

 

marks = {    101: 85,    102: 90,    103: 78 } print(marks[101])

 

Output:

85

 

This can be useful when student roll numbers are used as keys.

10.37 Dictionary with Boolean Values

Dictionaries are useful for storing status information.

 

attendance = {    "Aman": True,    "Ravi": False,    "Neha": True } print(attendance["Aman"])

 

Output:

True

 

You could interpret True as present and False as absent.

10.38 Example: Student Record

 

student = {    "name": "Aman",    "roll_no": 101,    "class": 10,    "section": "A",    "marks": 88 } print("Name:", student["name"]) print("Roll No:", student["roll_no"]) print("Class:", student["class"]) print("Section:", student["section"]) print("Marks:", student["marks"])

 

10.39 Updating a Student Record

 

student = {    "name": "Aman",    "class": 10,    "marks": 80 } student["marks"] = 92 student["section"] = "A" print(student)

 

The marks are updated and a new section field is added.

10.40 Example: Product Information

 

product = {    "name": "Laptop",    "price": 55000,    "brand": "ExampleBrand",    "stock": 10 } print("Product:", product["name"]) print("Price:", product["price"]) print("Stock:", product["stock"])

 

10.41 Example: Shopping Cart

A dictionary can be used to represent products and quantities.

 

cart = {    "Apples": 2,    "Milk": 1,    "Bread": 3 } for item, quantity in cart.items():    print(item, ":", quantity)

 

Output:

Apples : 2 Milk : 1 Bread : 3

 

10.42 Example: Word Frequency Counter

Dictionaries can be used to count how frequently words occur.

 

words = ["python", "html", "python", "css", "python", "html"] frequency = {} for word in words:    if word in frequency:        frequency[word] += 1    else:        frequency[word] = 1 print(frequency)

 

Output:

{'python': 3, 'html': 2, 'css': 1}

 

This is an important real-world use of dictionaries.

10.43 Using get() for Counting

The previous example can be simplified:

 

words = ["python", "html", "python", "css", "python", "html"] frequency = {} for word in words:    frequency[word] = frequency.get(word, 0) + 1 print(frequency)

 

Output:

{'python': 3, 'html': 2, 'css': 1}

 

This is a common Python technique.

10.44 Example: Marks Analyzer

 

marks = {    "Maths": 85,    "Science": 90,    "English": 78,    "Computer": 95 } total = sum(marks.values()) average = total / len(marks) print("Total:", total) print("Average:", average)

 

Output:

Total: 348 Average: 87.0

 

10.45 Finding the Highest Marks

 

marks = {    "Maths": 85,    "Science": 90,    "English": 78,    "Computer": 95 } highest_subject = max(marks, key=marks.get) print("Highest marks:", highest_subject) print("Marks:", marks[highest_subject])

 

Output:

Highest marks: Computer Marks: 95

 

10.46 Sorting a Dictionary by Keys

You can use sorted() to process dictionary keys in sorted order.

 

marks = {    "Science": 90,    "Maths": 85,    "English": 78 } for subject in sorted(marks):    print(subject, marks[subject])

 

Output:

English 78 Maths 85 Science 90

 

10.47 Sorting by Values

You can sort dictionary items according to their values.

 

marks = {    "Maths": 85,    "Science": 90,    "English": 78 } sorted_marks = sorted(    marks.items(),    key=lambda item: item[1] ) print(sorted_marks)

 

This returns a list of key-value tuples sorted by marks.

10.48 Nested Dictionary Example

Consider a school with several students:

 

students = {    101: {        "name": "Aman",        "marks": 85    },    102: {        "name": "Ravi",        "marks": 90    },    103: {        "name": "Neha",        "marks": 92    } }

 

Access Neha's marks:

 

print(students[103]["marks"])

 

Output:

92

 

10.49 Looping Through a Nested Dictionary

 

students = {    101: {        "name": "Aman",        "marks": 85    },    102: {        "name": "Ravi",        "marks": 90    },    103: {        "name": "Neha",        "marks": 92    } } for roll_no, details in students.items():    print("Roll No:", roll_no)    print("Name:", details["name"])    print("Marks:", details["marks"])    print()

 

This structure is useful for representing records.

10.50 Dictionary vs List

FeatureListDictionary
StoresValuesKey-value pairs
AccessIndexKey
Examplestudents[0]student["name"]
DuplicatesAllowedKeys must be unique
MutableYesYes
Best forOrdered collectionRelated labeled data

10.51 Dictionary vs Set

FeatureDictionarySet
StoresKey-value pairsValues
Duplicate valuesValues can repeatNo duplicate elements
Access by keyYesNo
Syntax{"name": "Aman"}{"Aman", "Ravi"}
Main useStructured dataUnique data

10.52 Important Dictionary Rules

Remember these rules:

  1. Dictionaries store key-value pairs.
  2. Keys must be unique.
  3. A key can map to any valid Python value.
  4. Values can be duplicated.
  5. Dictionaries are mutable.
  6. Dictionary keys must be hashable.
  7. Use get() when a key may not exist.
  8. Use items() to loop through keys and values.
  9. Use update() to add or modify multiple entries.

10.53 Common Mistakes

Mistake 1: Using a missing key

 

student = {"name": "Aman"} print(student["age"])

 

This raises a KeyError.

Safer:

 

print(student.get("age"))

 

Mistake 2: Using duplicate keys

 

student = {    "name": "Aman",    "name": "Ravi" }

 

The later value replaces the earlier value.

The dictionary effectively contains:

 

{"name": "Ravi"}

 

Mistake 3: Confusing keys and values

For:

 

student = {    "name": "Aman" }

 

"name" is the key and "Aman" is the value.

10.54 Mini Project: Student Management System

 

students = {    101: {        "name": "Aman",        "class": 10,        "marks": 85    },    102: {        "name": "Ravi",        "class": 10,        "marks": 90    },    103: {        "name": "Neha",        "class": 10,        "marks": 92    } } for roll_no, student in students.items():    print("Roll No:", roll_no)    print("Name:", student["name"])    print("Class:", student["class"])    print("Marks:", student["marks"])    print("----------------")

 

This demonstrates how dictionaries can be used to store structured student information.

10.55 Mini Project: Simple Phone Book

 

phone_book = {    "Aman": "9876543210",    "Ravi": "9123456780",    "Neha": "9988776655" } name = input("Enter name: ") if name in phone_book:    print("Phone:", phone_book[name]) else:    print("Contact not found")

 

10.56 Mini Project: Product Inventory

 

inventory = {    "Laptop": 5,    "Mouse": 20,    "Keyboard": 12,    "Monitor": 7 } for product, quantity in inventory.items():    print(product, ":", quantity) inventory["Mouse"] += 5 print("\nUpdated inventory:") print(inventory)

 

10.57 Chapter Summary

In this chapter, you learned:

  • What dictionaries are
  • Key-value pairs
  • Creating dictionaries
  • Empty dictionaries
  • Accessing values
  • get()
  • Adding new items
  • Updating values
  • update()
  • pop()
  • popitem()
  • del
  • clear()
  • Checking keys
  • keys()
  • values()
  • items()
  • Copying dictionaries
  • Nested dictionaries
  • Dictionary comprehension
  • Using dict()
  • Using zip()
  • Counting with dictionaries
  • Sorting dictionaries
  • Practical dictionary applications

The most important concept is:

A dictionary stores information as key-value pairs, allowing you to retrieve data using meaningful keys.

Quick Revision Questions

1. What is a dictionary?

A dictionary is a mutable collection that stores data in key-value pairs.

2. How do you create a dictionary?

 

student = {    "name": "Aman",    "marks": 85 }

 

3. How do you access a value?

 

student["name"]

 

4. What does get() do?

It retrieves a value for a key and can return a default value if the key is missing.

5. How do you add a new key?

 

student["city"] = "Bhopal"

 

6. Which method updates multiple key-value pairs?

update().

7. Which method returns all keys?

keys().

8. Which method returns all values?

values().

9. Which method returns key-value pairs?

items().

10. Can dictionary keys be duplicated?

No. Each key must be unique.

11. Can dictionary values be duplicated?

Yes.

12. Can a dictionary contain another dictionary?

Yes. This is called a nested dictionary.

Practice Exercises

Exercise 1: Create a Dictionary

Create a dictionary containing:

  • Name
  • Age
  • City
  • Profession

Display all values.

Exercise 2: Student Marks

Create a dictionary containing five subjects and their marks. Calculate the total and average.

Exercise 3: Update Data

Create a student dictionary and update the student's marks and class.

Exercise 4: Add Data

Add a new "email" key to an existing dictionary.

Exercise 5: Remove Data

Create a dictionary and remove one item using pop().

Exercise 6: Check a Key

Ask the user for a key and check whether it exists in the dictionary.

Exercise 7: Phone Book

Create a simple phone book using a dictionary and allow the user to search for a person's phone number.

Exercise 8: Word Counter

Given a list of words, create a dictionary containing the frequency of each word.

Exercise 9: Nested Dictionary

Create a dictionary containing records for three students. Each student should have a name, class, and marks.

Exercise 10: Dictionary Comprehension

Create a dictionary containing numbers from 1 to 10 as keys and their squares as values.

Chapter Activity

Create a Student Result Management System using Dictionaries.

Your program should store at least three students.

Each student record should contain:

  • Roll number
  • Name
  • Class
  • Maths marks
  • Science marks
  • English marks

The program should:

  1. Display all student records.
  2. Search for a student using roll number.
  3. Calculate total marks.
  4. Calculate average marks.
  5. Find the student with the highest marks.
  6. Update a student's marks.
  7. Add a new student.
  8. Remove a student.
  9. Display all students using a for loop.

This activity will combine dictionaries, nested dictionaries, loops, conditions, functions, and basic calculations.