1.11 From Keys to Values: Understanding Python Dictionaries

🗝️ From Keys to Values: Understanding Python Dictionaries

Class XI Computer Science – Python Notes | Unit: Data Structures

A Dictionary in Python is an unordered collection of key–value pairs. Each key is unique and acts as an identifier for its value. Dictionaries are extremely useful when you need to associate data in pairs, such as names with phone numbers, or employee IDs with salaries.


🔹 Creating a Dictionary

You can create a dictionary using curly braces { } or the dict() constructor.

# Example 1
student = {'name': 'Amit', 'class': 11, 'marks': 92}

# Example 2
employee = dict(id=101, name='Riya', salary=45000)

Output:

{'name': 'Amit', 'class': 11, 'marks': 92}
{'id': 101, 'name': 'Riya', 'salary': 45000}

🔹 Accessing Items in a Dictionary

You can access values by referring to their keys.

print(student['name'])       # Output: Amit
print(employee.get('salary')) # Output: 45000

Note: The get() method is safer than using square brackets, as it doesn’t give an error if the key doesn’t exist.


🔹 Mutability of a Dictionary

Dictionaries are mutable, meaning you can add, modify, or delete items after creation.

✅ Adding a new item

student['age'] = 16

✅ Modifying an existing item

student['marks'] = 95

✅ Deleting an item

del student['class']

✅ Clearing the dictionary

student.clear()

🔹 Traversing a Dictionary

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

for key in student:
    print(key, ":", student[key])

Output:

name : Amit
class : 11
marks : 95
age : 16

🔹 Built-in Functions and Methods

Python provides several built-in methods to work efficiently with dictionaries.

Function/Method Description Example
len() Returns number of items len(student)
keys() Returns all keys student.keys()
values() Returns all values student.values()
items() Returns key-value pairs student.items()
get(key) Returns value for key student.get('marks')
update() Updates dictionary with another student.update({'grade':'A'})
del Deletes a specific key del student['name']
clear() Removes all items student.clear()
fromkeys() Creates a new dictionary from keys dict.fromkeys(['a','b'], 0)
copy() Returns a shallow copy student.copy()
pop() Removes specified key and returns value student.pop('age')
popitem() Removes last inserted item student.popitem()
setdefault() Returns value if key exists, else adds key with default value student.setdefault('city','Delhi')
max(), min() Returns key with highest/lowest value (by key) max(student)
sorted() Returns sorted list of keys sorted(student)

💡 Suggested Programs

1️⃣ Count the number of times each character appears in a string

string = "success"
count = {}
for ch in string:
    count[ch] = count.get(ch, 0) + 1
print(count)

Output: {'s': 3, 'u': 1, 'c': 2, 'e': 1}

2️⃣ Create a dictionary of employees and access salary

employees = {
    'Riya': 50000,
    'Amit': 55000,
    'Neha': 48000
}

print("Salary of Amit:", employees['Amit'])

Output: Salary of Amit: 55000


📘 Summary

  • Dictionary stores data in key–value pairs.
  • It is mutable – we can modify, add or delete items anytime.
  • Supports powerful built-in methods for easy manipulation.
  • Perfect for storing and managing structured data.

💬 In short: Python Dictionaries are like mini-databases — organized, flexible, and lightning-fast for lookups!

Previous Post Next Post