home
0%
Progress
StudentPortal › Class XI - CS › Unit 2
CBSE Code 083 | Unit 2: Computational Thinking & Programming

08. Dictionaries in Python

Dictionary creation, key-value pairs, methods (get, keys, values, items, update, pop), iteration.

Unit 2: Computational Thinking & Programming

Chapter 8: Dictionaries in Python

1. Introduction to Dictionaries

A Dictionary is an unordered (insertion-ordered since Python 3.7), mutable collection of Key-Value pairs enclosed in curly braces {}.

$$\text{Dictionary} = {\text{key}_1: \text{value}_1, \text{key}_2: \text{value}_2, \dots}$$

Rules for Dictionary Keys:

  1. Keys must be of an immutable data type (e.g., int, float, str, tuple). A list or dict cannot be a key.
  2. Keys must be unique. If duplicate keys are specified, the last value overwrites previous ones.
  3. Values can be of any data type (mutable, immutable, nested) and can repeat.
# Valid dictionary
student = {
    "roll_no": 101,
    "name": "Diya",
    "subjects": ["Physics", "Chemistry", "CS"],
    "percentage": 94.2
}

2. Accessing, Adding, and Modifying Items

Accessing Values

  • Square Bracket Notation d[key]: Returns value; raises KeyError if key does not exist.
  • The get(key[, default]) Method: Returns value; returns default (or None) if key is absent without throwing an error.
d = {"CS": 83, "IP": 65, "Math": 41}
print(d["CS"])              # 83
print(d.get("Physics", 0))  # 0 (Safe access)

Adding and Modifying Key-Value Pairs

d["English"] = 92  # Adds new key "English"
d["CS"] = 99       # Modifies existing key "CS"

Deleting Items

  • del d[key]: Deletes specified key-value pair.
  • d.pop(key): Removes key and returns its associated value.
  • d.popitem(): Removes and returns the last inserted (key, value) tuple.
  • d.clear(): Empties the dictionary completely.

3. Built-in Dictionary Methods

Method Description Example
len(d) Number of key-value pairs. len({"a": 1, "b": 2}) $\to$ 2
d.keys() Returns a view object of all keys. d.keys() $\to$ dict_keys(['a', 'b'])
d.values() Returns a view object of all values. d.values() $\to$ dict_values([1, 2])
d.items() Returns view object of (key, value) tuples. d.items() $\to$ dict_items([('a', 1), ...])
d.update(other) Merges another dictionary or key-value pairs. d.update({"c": 3})
key in d Checks if key exists in dictionary. 'a' in d $\to$ True

4. Iterating Over a Dictionary

scores = {"Amit": 88, "Sneha": 95, "Rohit": 78}

# 1. Iterating over keys
for name in scores:
    print(name, "->", scores[name])

# 2. Iterating over keys and values simultaneously
for name, marks in scores.items():
    print(f"Student: {name:8} Marks: {marks}")

5. Classic Dictionary Programs for Practical Exams

Program 1: Frequency Count of Words in a Sentence

sentence = input("Enter a sentence: ").lower()
words = sentence.split()
freq = {}

for word in words:
    freq[word] = freq.get(word, 0) + 1

for word, count in freq.items():
    print(f"'{word}': {count}")

Program 2: Student Marks and Highest Scorer

n = int(input("Enter number of students: "))
students = {}

for _ in range(n):
    name = input("Enter student name: ")
    marks = float(input(f"Enter marks for {name}: "))
    students[name] = marks

# Find topper
topper = max(students, key=students.get)
print(f"Class Topper: {topper} with {students[topper]} marks!")

6. Board Exam Practice Questions & Solutions

Q1. Identify which of the following are valid keys in a Python dictionary: 1. 45 2. 'roll_no' 3. [1, 2, 3] 4. (1, 2, 3) 5. {"a": 1} Answer:
- 45: Valid (integer is immutable).
- 'roll_no': Valid (string is immutable).
- [1, 2, 3]: Invalid (list is mutable and cannot be hashed).
- (1, 2, 3): Valid (tuple with immutable contents is immutable).
- {"a": 1}: Invalid (dict is mutable).

Q2. Find the output of the following code:

inventory = {"Pen": 50, "Pencil": 30, "Notebook": 20}
inventory["Pencil"] = 45
inventory["Eraser"] = 15
print("Items:", len(inventory))
print("Pencil count:", inventory.get("Pencil"))
print("Ruler count:", inventory.get("Ruler", 0))

Answer:

Items: 4
Pencil count: 45
Ruler count: 0

Entity Details

Create New Item

help

Submit Technical Query

Have a question or run into an issue? Describe it below, upload an optional screenshot, and our engineering team will answer it!

image Attach image (optional)

Submit Feedback

build Free Developer Utility Free Tool
gavel

Privacy & Legal Disclaimer

1. Client-Side Browser Processing

All utility tools on DeepEngineerHub (including Image to PDF, Text Formatters, JSON Converters, and Encryptors) execute 100% locally within your client browser using WebAssembly and JavaScript. No uploaded images, text, or documents are transmitted, collected, or stored on remote servers.

2. Limitation of Liability ("As-Is" Provision)

Tools and services are provided free of charge for convenience and educational purposes "as-is" without warranties of any kind. DeepEngineerHub shall not be held liable for any data loss, formatting inconsistencies, or indirect damages resulting from tool usage.

3. Open Source & Third-Party Software

Certain utilities utilize open-source client libraries (such as jsPDF, Mermaid.js, Pyodide) licensed under MIT, Apache, or BSD open licenses. All intellectual property remains with their respective copyright holders.