1.d.Mapping
1.d.Mapping
A dictionary (dict) is a mapping data type in Python that stores data in key-value pairs.
Each key maps to a specific value, making it efficient for fast lookups.
Characteristics of a Dictionary
✅ Unordered – Items are stored in no particular order (since Python 3.7, dictionaries maintain insertion
order).
✅ Mutable – Can be modified (keys and values can be added, updated, or removed).
✅ Unique Keys – Keys must be unique (no duplicates allowed).
✅ Fast Lookup – Searching for values by key is very fast.
✅ Uses {} Braces – Defined using curly braces {} or the dict() constructor.
1. Creating a Dictionary
A dictionary is created using curly braces {} with key-value pairs separated by a colon :.
# Creating a dictionary
student = {
"name": "Alice",
"age": 22,
"course": "Computer Science"
}
print(student)
Output:
Output:
# Accessing values
print(student["name"]) # Output: Alice
print(student["age"]) # Output: 22
3. Modifying a Dictionary
Updating Values
student["age"] = 23 # Modify an existing key
print(student) # Output: {'name': 'Alice', 'age': 23, 'course': 'Computer Science'}
4. Removing Elements
Using pop() – Removes Key and Returns Value
age = student.pop("age")
print(age) # Output: 23
print(student) # Output: {'name': 'Alice', 'course': 'Computer Science', 'grade': 'A'}
Output:
name : Alice
age : 22
course : Computer Science
6. Dictionary Methods
Method Description
dict.keys() Returns all keys
dict.values() Returns all values
dict.items() Returns key-value pairs
dict.get(key, default) Returns value or default if key not found
dict.pop(key) Removes a key and returns its value
dict.popitem() Removes and returns the last key-value pair
dict.clear() Removes all items
dict.update(dict2) Merges another dictionary into it
7. Nested Dictionaries
A dictionary can contain another dictionary as a value.
students = {
"Alice": {"age": 22, "course": "CS"},
"Bob": {"age": 21, "course": "IT"}
}
print(students["Alice"]["course"]) # Output: CS
8. Dictionary Comprehension
Creating a Dictionary with Squares of Numbers
squares = {x: x*x for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
9. Practical Examples
Example 1: Counting Word Frequency in a Sentence
sentence = "apple banana apple mango banana apple"
words = sentence.split()
word_count = {}
Output:
Summary
Feature Dictionary (dict)
Mutable? Yes
Ordered? Yes (since Python 3.7)
Unique Keys? Yes
Fast Lookup? Yes
Nested? Yes