Python Programming for Beginners

fgdfhd

<h2>10.1 Introduction</h2>

<p>
Python dictionaries are one of the most useful data structures in Python.
A dictionary stores information in the form of <strong>key-value pairs</strong>.
Each key is used to access its corresponding value.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 85
}

print(student)</code></pre>

<p>
In this example, <strong>name</strong>, <strong>age</strong>, and
<strong>marks</strong> are keys, while <strong>Aman</strong>, 
<strong>16</strong>, and <strong>85</strong> are their values.
</p>


<h2>10.2 What is a Dictionary?</h2>

<p>
A dictionary is a collection of key-value pairs. Dictionaries are useful
when data needs to be stored with meaningful labels.
</p>

<pre><code>student = {
   "name": "Aman",
   "class": 10,
   "marks": 88
}

print(student)</code></pre>

<p>Output:</p>

<pre><code>{'name': 'Aman', 'class': 10, 'marks': 88}</code></pre>


<h2>10.3 Creating a Dictionary</h2>

<p>
Dictionaries are normally created using curly brackets
<strong>{ }</strong>.
</p>

<pre><code>person = {
   "name": "Ravi",
   "age": 20,
   "city": "Bhopal"
}

print(person)</code></pre>

<p>
A dictionary can contain values of different data types.
</p>


<h2>10.4 Creating an Empty Dictionary</h2>

<p>
An empty dictionary can be created using <code>{}</code> or
<code>dict()</code>.
</p>

<pre><code>data = {}

print(data)

another_data = dict()

print(another_data)</code></pre>


<h2>10.5 Key-Value Pairs</h2>

<p>
Every dictionary item contains a key and a value separated by a colon
<strong>:</strong>.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16
}</code></pre>

<p>The structure can be understood as:</p>

<ul>
   <li><strong>name</strong> → Aman</li>
   <li><strong>age</strong> → 16</li>
</ul>


<h2>10.6 Accessing Dictionary Values</h2>

<p>
A dictionary value can be accessed using its key.
</p>

<pre><code>student = {
   "name": "Aman",
   "marks": 85
}

print(student["name"])
print(student["marks"])</code></pre>

<p>Output:</p>

<pre><code>Aman
85</code></pre>


<h2>10.7 Using the get() Method</h2>

<p>
The <code>get()</code> method can also be used to retrieve a value.
It is especially useful when a key may not exist.
</p>

<pre><code>student = {
   "name": "Aman",
   "marks": 85
}

print(student.get("name"))</code></pre>

<p>Output:</p>

<pre><code>Aman</code></pre>


<h2>10.8 get() with a Default Value</h2>

<p>
If the requested key does not exist, <code>get()</code> can return a
default value instead of producing an error.
</p>

<pre><code>student = {
   "name": "Aman"
}

print(student.get("age", "Not available"))</code></pre>

<p>Output:</p>

<pre><code>Not available</code></pre>


<h2>10.9 Adding a New Item</h2>

<p>
A new key-value pair can be added by assigning a value to a new key.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16
}

student["city"] = "Bhopal"

print(student)</code></pre>


<h2>10.10 Updating an Existing Value</h2>

<p>
If a key already exists, assigning a new value updates the existing value.
</p>

<pre><code>student = {
   "name": "Aman",
   "marks": 80
}

student["marks"] = 90

print(student)</code></pre>

<p>Output:</p>

<pre><code>{'name': 'Aman', 'marks': 90}</code></pre>


<h2>10.11 Updating Multiple Values</h2>

<p>
The <code>update()</code> method can be used to update multiple
key-value pairs at once.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 80
}

student.update({
   "age": 17,
   "marks": 90
})

print(student)</code></pre>


<h2>10.12 Removing an Item with pop()</h2>

<p>
The <code>pop()</code> method removes the specified key and returns
its value.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 85
}

removed = student.pop("age")

print("Removed:", removed)
print(student)</code></pre>


<h2>10.13 Removing an Item with del</h2>

<p>
The <code>del</code> statement can be used to remove a particular
key-value pair.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 85
}

del student["age"]

print(student)</code></pre>


<h2>10.14 Using popitem()</h2>

<p>
The <code>popitem()</code> method removes and returns the last
inserted key-value pair.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 85
}

item = student.popitem()

print(item)
print(student)</code></pre>


<h2>10.15 Clearing a Dictionary</h2>

<p>
The <code>clear()</code> method removes all key-value pairs from
a dictionary.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16
}

student.clear()

print(student)</code></pre>

<p>Output:</p>

<pre><code>{}</code></pre>


<h2>10.16 Checking Whether a Key Exists</h2>

<p>
The <code>in</code> operator can be used to check whether a key exists.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16
}

if "name" in student:
   print("Name is available")</code></pre>

<p>Output:</p>

<pre><code>Name is available</code></pre>


<h2>10.17 Finding the Number of Items</h2>

<p>
The <code>len()</code> function returns the number of key-value pairs.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 85
}

print(len(student))</code></pre>

<p>Output:</p>

<pre><code>3</code></pre>


<h2>10.18 Dictionary Keys</h2>

<p>
Dictionary keys must be suitable hashable values. Strings and numbers
are commonly used as keys.
</p>

<pre><code>marks = {
   101: 85,
   102: 90,
   103: 78
}

print(marks[101])</code></pre>

<p>Output:</p>

<pre><code>85</code></pre>


<h2>10.19 Dictionary Values</h2>

<p>
Dictionary values can be of many different types, including strings,
numbers, Boolean values, lists, tuples, sets, and other dictionaries.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 88.5,
   "passed": True
}

print(student)</code></pre>


<h2>10.20 Dictionary with a List</h2>

<p>
A list can be stored as a dictionary value.
</p>

<pre><code>student = {
   "name": "Aman",
   "subjects": ["Maths", "Science", "English"]
}

print(student["subjects"])</code></pre>

<p>
You can also access an individual element from the list.
</p>

<pre><code>print(student["subjects"][0])</code></pre>

<p>Output:</p>

<pre><code>Maths</code></pre>


<h2>10.21 Looping Through a Dictionary</h2>

<p>
A <code>for</code> loop can be used to iterate through dictionary keys.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 85
}

for key in student:
   print(key)</code></pre>


<h2>10.22 Using keys()</h2>

<p>
The <code>keys()</code> method provides the dictionary's keys.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 85
}

for key in student.keys():
   print(key)</code></pre>


<h2>10.23 Using values()</h2>

<p>
The <code>values()</code> method provides the dictionary's values.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 85
}

for value in student.values():
   print(value)</code></pre>


<h2>10.24 Using items()</h2>

<p>
The <code>items()</code> method allows you to access both keys and
values while looping.
</p>

<pre><code>student = {
   "name": "Aman",
   "age": 16,
   "marks": 85
}

for key, value in student.items():
   print(key, ":", value)</code></pre>

<p>Output:</p>

<pre><code>name : Aman
age : 16
marks : 85</code></pre>


<h2>10.25 keys(), values() and items()</h2>

<table>
   <thead>
       <tr>
           <th>Method</th>
           <th>Purpose</th>
       </tr>
   </thead>
   <tbody>
       <tr>
           <td><code>keys()</code></td>
           <td>Provides dictionary keys</td>
       </tr>
       <tr>
           <td><code>values()</code></td>
           <td>Provides dictionary values</td>
       </tr>
       <tr>
           <td><code>items()</code></td>
           <td>Provides key-value pairs</td>
       </tr>
   </tbody>
</table>


<h2>10.26 Nested Dictionaries</h2>

<p>
A dictionary can contain another dictionary as a value.
This is called a <strong>nested dictionary</strong>.
</p>

<pre><code>students = {
   "student1": {
       "name": "Aman",
       "marks": 85
   },
   "student2": {
       "name": "Ravi",
       "marks": 90
   }
}

print(students)</code></pre>


<h2>10.27 Accessing a Nested Dictionary</h2>

<pre><code>students = {
   "student1": {
       "name": "Aman",
       "marks": 85
   },
   "student2": {
       "name": "Ravi",
       "marks": 90
   }
}

print(students["student1"]["name"])
print(students["student2"]["marks"])</code></pre>

<p>Output:</p>

<pre><code>Aman
90</code></pre>


<h2>10.28 Copying a Dictionary</h2>

<p>
The <code>copy()</code> method can be used to create a shallow copy
of a dictionary.
</p>

<pre><code>student = {
   "name": "Aman",
   "marks": 85
}

student_copy = student.copy()

print(student_copy)</code></pre>


<h2>10.29 Dictionary Comprehension</h2>

<p>
Dictionary comprehension provides a short way to create dictionaries.
</p>

<pre><code>numbers = [1, 2, 3, 4, 5]

squares = {
   number: number ** 2
   for number in numbers
}

print(squares)</code></pre>

<p>Output:</p>

<pre><code>{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}</code></pre>


<h2>10.30 Dictionary Comprehension with a Condition</h2>

<pre><code>numbers = range(1, 11)

even_squares = {
   number: number ** 2
   for number in numbers
   if number % 2 == 0
}

print(even_squares)</code></pre>

<p>Output:</p>

<pre><code>{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}</code></pre>


<h2>10.31 Creating a Dictionary with dict()</h2>

<pre><code>student = dict(
   name="Aman",
   age=16,
   marks=85
)

print(student)</code></pre>


<h2>10.32 Creating a Dictionary Using zip()</h2>

<p>
The <code>zip()</code> function can be combined with <code>dict()</code>
to create a dictionary from two sequences.
</p>

<pre><code>keys = ["name", "age", "city"]
values = ["Aman", 16, "Bhopal"]

student = dict(zip(keys, values))

print(student)</code></pre>


<h2>10.33 Example: Student Record</h2>

<pre><code>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"])</code></pre>


<h2>10.34 Example: Student Marks Analyzer</h2>

<pre><code>marks = {
   "Maths": 85,
   "Science": 90,
   "English": 78,
   "Computer": 95
}

total = sum(marks.values())
average = total / len(marks)

print("Total:", total)
print("Average:", average)</code></pre>

<p>Output:</p>

<pre><code>Total: 348
Average: 87.0</code></pre>


<h2>10.35 Example: Word Frequency Counter</h2>

<p>
Dictionaries are commonly used to count how many times values occur.
</p>

<pre><code>words = [
   "python",
   "html",
   "python",
   "css",
   "python",
   "html"
]

frequency = {}

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

print(frequency)</code></pre>

<p>Output:</p>

<pre><code>{'python': 3, 'html': 2, 'css': 1}</code></pre>


<h2>10.36 Example: Phone Book</h2>

<pre><code>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")</code></pre>


<h2>10.37 Example: Product Inventory</h2>

<pre><code>inventory = {
   "Laptop": 5,
   "Mouse": 20,
   "Keyboard": 12,
   "Monitor": 7
}

for product, quantity in inventory.items():
   print(product, ":", quantity)

inventory["Mouse"] += 5

print("Updated inventory:")
print(inventory)</code></pre>


<h2>10.38 Dictionary vs List</h2>

<table>
   <thead>
       <tr>
           <th>Feature</th>
           <th>List</th>
           <th>Dictionary</th>
       </tr>
   </thead>
   <tbody>
       <tr>
           <td>Stores</td>
           <td>Values</td>
           <td>Key-value pairs</td>
       </tr>
       <tr>
           <td>Access</td>
           <td>Index</td>
           <td>Key</td>
       </tr>
       <tr>
           <td>Mutable</td>
           <td>Yes</td>
           <td>Yes</td>
       </tr>
       <tr>
           <td>Main use</td>
           <td>Collection of values</td>
           <td>Structured and labelled data</td>
       </tr>
   </tbody>
</table>


<h2>10.39 Dictionary vs Set</h2>

<table>
   <thead>
       <tr>
           <th>Feature</th>
           <th>Dictionary</th>
           <th>Set</th>
       </tr>
   </thead>
   <tbody>
       <tr>
           <td>Stores</td>
           <td>Key-value pairs</td>
           <td>Unique values</td>
       </tr>
       <tr>
           <td>Access by key</td>
           <td>Yes</td>
           <td>No</td>
       </tr>
       <tr>
           <td>Duplicates</td>
           <td>Keys are unique</td>
           <td>Elements are unique</td>
       </tr>
       <tr>
           <td>Main use</td>
           <td>Structured data</td>
           <td>Unique data and set operations</td>
       </tr>
   </tbody>
</table>


<h2>10.40 Common Mistakes</h2>

<h3>Mistake 1: Accessing a Missing Key</h3>

<pre><code>student = {
   "name": "Aman"
}

print(student["age"])</code></pre>

<p>
The above code raises a <code>KeyError</code> because the key
<strong>age</strong> does not exist.
</p>

<p>A safer approach is:</p>

<pre><code>print(student.get("age"))</code></pre>


<h3>Mistake 2: Using Duplicate Keys</h3>

<pre><code>student = {
   "name": "Aman",
   "name": "Ravi"
}

print(student)</code></pre>

<p>
Dictionary keys should be unique. If the same key is written more than
once, the later value replaces the earlier value.
</p>


<h2>10.41 Mini Project: Student Management System</h2>

<p>
The following program uses nested dictionaries to store information
about multiple students.
</p>

<pre><code>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("----------------")</code></pre>


<h2>10.42 Chapter Summary</h2>

<p>In this chapter, you learned:</p>

<ul>
   <li>What dictionaries are</li>
   <li>Key-value pairs</li>
   <li>Creating dictionaries</li>
   <li>Accessing values</li>
   <li>Using <code>get()</code></li>
   <li>Adding new items</li>
   <li>Updating values</li>
   <li>Removing items</li>
   <li>Using <code>keys()</code></li>
   <li>Using <code>values()</code></li>
   <li>Using <code>items()</code></li>
   <li>Nested dictionaries</li>
   <li>Dictionary comprehension</li>
   <li>Counting values with dictionaries</li>
   <li>Practical dictionary applications</li>
</ul>

<p>
<strong>Remember:</strong> A dictionary stores information using
<strong>key-value pairs</strong>, making it easy to organize and
retrieve related data.
</p>


<h2>10.43 Quick Revision Questions</h2>

<ol>
   <li>What is a dictionary?</li>
   <li>What is a key-value pair?</li>
   <li>How do you create an empty dictionary?</li>
   <li>How can you access a dictionary value?</li>
   <li>What is the purpose of <code>get()</code>?</li>
   <li>How do you add a new key-value pair?</li>
   <li>What does <code>update()</code> do?</li>
   <li>What is the difference between <code>pop()</code> and <code>del</code>?</li>
   <li>What do <code>keys()</code>, <code>values()</code>, and <code>items()</code> return?</li>
   <li>What is a nested dictionary?</li>
</ol>


<h2>10.44 Practice Exercises</h2>

<ol>
   <li>Create a dictionary containing your name, age, city and profession.</li>
   <li>Create a dictionary containing five subjects and their marks.</li>
   <li>Calculate the total and average marks.</li>
   <li>Add a new key to an existing dictionary.</li>
   <li>Update an existing dictionary value.</li>
   <li>Remove an item using <code>pop()</code>.</li>
   <li>Check whether a particular key exists.</li>
   <li>Create a simple phone book using a dictionary.</li>
   <li>Create a nested dictionary containing three student records.</li>
   <li>Create a dictionary using dictionary comprehension.</li>
</ol>


<h2>10.45 Chapter Activity</h2>

<p>
Create a <strong>Student Result Management System</strong> using
dictionaries.
</p>

<p>Your program should store:</p>

<ul>
   <li>Roll number</li>
   <li>Name</li>
   <li>Class</li>
   <li>Maths marks</li>
   <li>Science marks</li>
   <li>English marks</li>
</ul>

<p>The program should:</p>

<ol>
   <li>Display all student records.</li>
   <li>Search for a student using roll number.</li>
   <li>Calculate total marks.</li>
   <li>Calculate average marks.</li>
   <li>Find the student with the highest marks.</li>
   <li>Update a student's marks.</li>
   <li>Add a new student.</li>
   <li>Remove a student.</li>
   <li>Display all students using a loop.</li>
</ol>


<h2>What's Next?</h2>

<p>
<strong>Next Chapter: Python Strings – Creating, Formatting, Indexing,
Slicing and String Methods</strong>
</p>