Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 9: Dictionaries in Python

A dictionary is an unordered collection of items where each item is stored as a Key-Value pair. Dictionaries are mutable, but the keys inside a dictionary must be immutable (like strings, numbers, or tuples) and unique. Dictionaries are enclosed in curly braces {}.

9.1 Accessing and Modifying Items

Unlike lists, dictionaries do not use numeric indexing. You access values using their corresponding keys.

# Creating a dictionary
student = {'name': 'Rohan', 'age': 16, 'grade': 'A'}

# Accessing a value
print(student['name'])  # Output: Rohan

# Adding a new term / Modifying an existing item
student['marks'] = 95   # Adds a new key-value pair
student['grade'] = 'A+' # Modifies existing value

Note: Attempting to access a key that doesn’t exist using dict[key] will raise a KeyError.

9.2 Traversing a Dictionary

You can loop through a dictionary to access its keys, values, or both.

# Loop through keys
for k in student:
    print(k, student[k])

9.3 Built-in Functions and Methods

Dictionaries come with a rich set of methods.

  • len(dict): Returns the number of key-value pairs.
  • dict(): Constructor to create a dictionary.
  • keys(): Returns a sequence of all keys.
  • values(): Returns a sequence of all values.
  • items(): Returns a sequence of tuples representing key-value pairs (key, value).
  • get(key, [default]): Returns the value for key. If key is not found, returns default (or None). Avoids KeyError.
  • update(other_dict): Updates the dictionary with key-value pairs from another dictionary.
  • del dict[key]: Deletes the specified key-value pair.
  • clear(): Removes all elements from the dictionary.
  • pop(key, [default]): Removes the item with key and returns its value.
  • popitem(): Removes and returns the last inserted key-value pair as a tuple.
  • setdefault(key, [default]): Returns the value of key. If key doesn’t exist, inserts key with default value.
  • fromkeys(sequence, [value]): Creates a new dictionary with keys from sequence and values set to value.
  • copy(): Returns a shallow copy of the dictionary.
  • max() / min() / sorted(): When applied to a dictionary, these operate on the keys by default.

9.4 Common Programs

1. Counting Character Frequency

A common use case for dictionaries is counting the occurrences of characters in a string.

text = "hello"
freq = {}
for char in text:
    if char in freq:
        freq[char] += 1
    else:
        freq[char] = 1
print(freq) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

Competency Based Questions

Q1. Predict the Output What will be the output of the following code?

D = {'a': 10, 'b': 20, 'c': 30}
D.update({'b': 40, 'd': 50})
print(D.pop('c'))
print(D)

Q2. Find the Error Kiran tries to create a dictionary where she uses a list as a key to map students to their subjects.

data = { ["Rahul", "Class11"] : "Computer Science" }
print(data)

Why does this result in a TypeError? How can it be fixed?

Q3. Case-Based Scenario A small company wants to store data for its 3 employees. For each employee, they need to store their Name as the key and their Salary as the value.

  1. Write Python code to create this dictionary for ‘Amit’ (Salary: 40000), ‘Sneha’ (Salary: 55000), and ‘John’ (Salary: 30000).
  2. Write a loop to print the names of employees earning more than 35000.

Q4. Assertion-Reasoning

  • Assertion (A): The get() method is safer to use than square brackets [] when accessing dictionary values.
  • Reason (R): If a key is not found, get() returns None (or a specified default value), whereas [] raises a KeyError and crashes the program. Choose the correct option: a) Both A and R are true and R is the correct explanation of A. b) Both A and R are true but R is NOT the correct explanation of A. c) A is true but R is false. d) A is false but R is true.

Answers to Competency Based Questions

A1.

30
{'a': 10, 'b': 40, 'd': 50}

Explanation:

  1. update() changes the value of ‘b’ to 40 and adds ‘d’: 50.
  2. pop('c') removes the key ‘c’ and returns its value (30).
  3. The final dictionary has keys ‘a’, ‘b’, and ‘d’.

A2. Error: Dictionary keys must be immutable. Lists are mutable, so they cannot be hashed and used as dictionary keys. Correction: Use a tuple instead of a list for the key, as tuples are immutable.

data = { ("Rahul", "Class11") : "Computer Science" }
print(data)

A3.

  1. Code to create the dictionary:
employees = {'Amit': 40000, 'Sneha': 55000, 'John': 30000}
  1. Code to print names earning > 35000:
for name, salary in employees.items():
    if salary > 35000:
        print(name)

A4. a) Both A and R are true and R is the correct explanation of A. get() provides a fail-safe mechanism, preventing runtime errors if a key is missing.