0% found this document useful (0 votes)
15 views6 pages

Python Dictionary Basics for CBSE Class 11

A Python dictionary is a mutable collection that stores data in key-value pairs, allowing for fast access and unique keys. It can be created using the syntax 'dictionary_name = {key1: value1, key2: value2}' and supports various operations such as adding, updating, and deleting elements. The document also includes examples, methods, and comparisons with lists, along with practice programs and important exam notes.

Uploaded by

priyamvada7302
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views6 pages

Python Dictionary Basics for CBSE Class 11

A Python dictionary is a mutable collection that stores data in key-value pairs, allowing for fast access and unique keys. It can be created using the syntax 'dictionary_name = {key1: value1, key2: value2}' and supports various operations such as adding, updating, and deleting elements. The document also includes examples, methods, and comparisons with lists, along with practice programs and important exam notes.

Uploaded by

priyamvada7302
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON DICTIONARY

Class 11 – CBSE Computer Science / Informatics Practices

1️⃣ What is a Dictionary in Python?


A dictionary is a collection of data that stores values in key : value pairs.

🔹 Real-Life Example
Think of a phone contact list:

●​ Name → Phone Number


●​ Roll Number → Student Name
●​ Product → Price

Just like:

Rahul → 9876543210
Aman → 9123456789

2️⃣ Why Use Dictionary?


Feature Description

Mutable Can be changed

Fast Access data using keys

Indexed by key Not by position

Unique keys No duplicate keys

Ordered (Python Maintains insertion order


3.7+)

3️⃣ Creating a Dictionary


🔹 Syntax
dictionary_name = {key1: value1, key2: value2}

🔹 Example 1: Student Marks


marks = {"Maths": 90, "Physics": 85, "Chemistry": 88}
print(marks)

🔹 Example 2: Phone Book


phone = {"Rahul": 9876543210, "Aman": 9123456789}

4️⃣ Accessing Dictionary Values


🔹 Using Key
print(marks["Maths"])

🔹 Using get() method


print([Link]("Physics"))

✔ Safer than [] because it does not give error if key is missing.

5️⃣ Adding New Elements


🔹 Example
marks["English"] = 92
print(marks)

🔹 Real-Life Example: Adding new contact


phone["Rohit"] = 9988776655
6️⃣ Updating Values
marks["Maths"] = 95
print(marks)

✔ Keys remain same, values change.

7️⃣ Deleting Elements

🔹 Using del
del marks["Physics"]

🔹 Using pop()
[Link]("Chemistry")

🔹 Using clear()
[Link]() # removes all elements

8️⃣ Dictionary Methods (VERY IMPORTANT FOR EXAM)

🔹 keys()
print([Link]())

🔹 values()
print([Link]())

🔹 items()
print([Link]())
9️⃣ Looping Through Dictionary
🔹 Loop through keys
for subject in marks:
print(subject)

🔹 Loop through values


for score in [Link]():
print(score)

🔹 Loop through key-value pairs


for subject, score in [Link]():
print(subject, ":", score)

🔟 Checking Key Exists or Not


if "Maths" in marks:
print("Maths is present")

1️⃣1️⃣ Length of Dictionary


print(len(marks))

1️⃣2️⃣ Nested Dictionary


A dictionary inside another dictionary.

🔹 Example: Student Database


students = {
101: {"Name": "Rahul", "Marks": 90},
102: {"Name": "Aman", "Marks": 85}
}
print(students[101]["Name"])

1️⃣3️⃣ Real-Life Examples


🔹 Example 1: Product Price List
products = {"Pen": 10, "Book": 50, "Bag": 800}

🔹 Example 2: Employee Salary


salary = {"Ravi": 25000, "Neha": 30000}

🔹 Example 3: Login System


users = {"admin": "1234", "user": "abcd"}

1️⃣4️⃣ Dictionary vs List


Dictionary List

Key-value pair Index based

Fast lookup Slower

Keys unique Values can


repeat

1️⃣5️⃣ Programs for Practice (EXAM BASED)


🔹 Program 1: Create dictionary and display
d = {"Name": "Riya", "Class": 11, "Section": "A"}
print(d)

🔹 Program 2: Sum of values


marks = {"Maths": 90, "Physics": 80, "Chemistry": 85}
total = sum([Link]())
print("Total Marks:", total)

🔹 Program 3: Count frequency of words


sentence = "apple banana apple mango banana"
words = [Link]()
freq = {}

for w in words:
freq[w] = [Link](w, 0) + 1

print(freq)

1️⃣6️⃣ Important Exam Notes ⭐



✔ Keys must be immutable (int, string, tuple)​
List cannot be a key​
✔ Values can be anything​
✔ Dictionary is mutable

1️⃣7️⃣ Short Answer for Exam

👉
Q: What is a dictionary in Python?​
A dictionary is a mutable data type that stores data in key-value pairs.

Common questions

Powered by AI

Nested dictionaries in Python facilitate complex data structures, like hierarchical databases, by allowing dictionaries to exist within other dictionaries. This structuring makes retrieval intuitive and maintains logical organization, resembling real-world relational data models. However, they can become difficult to manage if overly deep or large, complicating code readability and increasing potential for errors .

Here is the Python program: \n``` python\nmarks = {"Maths": 90, "Physics": 80, "Chemistry": 85}\ntotal = sum(marks.values())\nprint("Total Marks:", total)\n``` This program initializes a dictionary with subjects as keys and marks as values, sums the marks using `sum()` on `marks.values()` and prints the total, demonstrating effective aggregation using dictionaries .

The introduction of order retention in Python dictionaries starting from version 3.7 has simplified tasks that require maintaining the insertion order of elements, eliminating the need for the separate `OrderedDict` from the `collections` module for many common use cases. This change has made Python dictionaries more versatile and has likely encouraged their more frequent use in applications where order matters .

Exam-critical functions for dictionaries include `keys()`, `values()`, and `items()` for data iteration, `get()` for safe data access, and `pop()` for element removal, among others. These methods are emphasized because they encapsulate core functionalities of dictionaries, facilitating efficient data manipulation, which is essential for problem-solving tasks in computer science education .

The `get()` method in Python dictionaries is preferred over direct key access when there is a possibility that a key might not exist in the dictionary. Using `get()` prevents runtime errors by returning None or a specified default value when the key is not found, making it safer for keys whose presence is uncertain .

To remove duplicate values while preserving one key-value pair for each unique value, iterate through the dictionary and create a new dictionary. Check if the value is already in the new dictionary, and if not, add the key-value pair: """ python original = {"a": 1, "b": 1, "c": 2} unique_values = {} for key, value in original.items(): if value not in unique_values.values(): unique_values[key] = value """ This ensures that each unique value is associated with its first encountered key .

Looping through key-value pairs using the `items()` method allows direct access to both the key and the value simultaneously, simplifying operations that require a relationship between them. This method is more efficient and readable than separate loops through keys and lookups of corresponding values, enhancing code clarity and performance .

In Python dictionaries, keys must be of immutable data types such as integers, strings, or tuples, because immutability ensures hashability, which is required for the fast lookup feature of dictionaries. Values, however, can be mutable, allowing them to be updated or changed. This separation allows dictionaries to maintain a reliable indexing system while offering flexibility in value manipulation .

When using dictionaries for a user-login system, it is essential to ensure that username keys are unique and that passwords (stored as values) are handled securely, potentially leveraging hashing functions for storage rather than plain text. This setup optimizes the system for fast lookups, ensuring efficient verification of login credentials while maintaining security .

Dictionaries provide faster data lookup due to being indexed by keys rather than numeric positions. Additionally, they ensure that keys are unique, whereas a list allows duplicates and accesses data by index. Dictionaries maintain insertion order as of Python 3.7, thus offering ordered access to elements similar to lists but with the added benefit of named keys .

You might also like