- Create and print a dictionary Concept: A dictionary stores data in key–value pairs.
student = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
print(student)
Explanation:
Each key is linked to a value. This helps organize related data.
2.Access specific values
Concept: Access values using keys.
print(student["name"])
print(student["major"])
Explanation:
We use the key inside square brackets to get the value.
3.Add and update values
Concept: Dictionaries are mutable.
student["gpa"] = 3.8
student["age"] = 22
print(student)
Explanation:
New key-value pairs can be added, and existing ones can be updated.
4.Remove a key using del
Concept: Delete elements.
del student["major"]
print(student)
Explanation:
Removes the key and its value permanently.
5.Check if a key exists
Concept: Use in operator.
print("age" in student)
Explanation:
Returns True if the key exists, otherwise False.
6.Iterate through a dictionary
Concept: Loop through key-value pairs.
prices = {"apple": 0.5, "banana": 0.3, "orange": 0.7}
for key, value in prices.items():
print(key, value)
Explanation:
items() returns both keys and values together.
- Count key-value pairs Concept: Use len().
print(len(prices))
Explanation:
Gives total number of entries.
8.Use get() method
Concept: Safe access.
print(student.get("gpa"))
print(student.get("graduation_year", 2025))
Explanation:
If key doesn’t exist, default value is returned.
9.Merge dictionaries
Concept: Combine dictionaries.
extra_info = {
"graduation_year": 2025,
"hometown": "Springfield"
}
student.update(extra_info)
print(student)
Explanation:
update() adds all key-value pairs from another dictionary.
10.Dictionary comprehension
Concept: Create dictionary in one line.
squares = {x: x**2 for x in range(1, 6)}
print(squares)
Explanation:
Keys are numbers, values are their squares.
- Get keys and values separately Concept: Use keys() and values().
print(list(prices.keys()))
print(list(prices.values()))
Explanation:
Returns keys and values as lists.
12.Nested dictionary
Concept: Dictionary inside dictionary.
school = {
"student1": {"name": "Alice", "age": 21},
"student2": {"name": "Bob", "age": 22}
}
print(school["student2"]["age"])
Explanation:
Access nested values step by step.
- Use setdefault() Concept: Add key only if it doesn’t exist.
student.setdefault("advisor", "Dr. Smith")
print(student)
Explanation:
Prevents overwriting existing values.
- Use pop() Concept: Remove and store value.
value = student.pop("hometown")
print(value)
Explanation:
Removes key and returns its value.
15.Clear dictionary
Concept: Remove all items.
prices.clear()
print(prices)
Explanation:
Dictionary becomes empty {}.
16.Copy dictionary
Concept: Create duplicate.
copy_student = student.copy()
copy_student["name"] = "Charlie"
print(student)
print(copy_student)
Explanation:
Original dictionary remains unchanged.
17.Create dictionary using zip()
Concept: Combine two lists.
keys = ["name", "age", "major"]
values = ["Eve", 20, "Mathematics"]
new_dict = dict(zip(keys, values))
print(new_dict)
Explanation:
Pairs elements from both lists.
18.Iterate using items()
Concept: Loop through dictionary.
for key, value in student.items():
print(key, value)
Explanation:
Useful for accessing both key and value together.
19.Count occurrences (manual method)
Concept: Frequency counting.
fruits = ["apple", "banana", "apple", "orange", "banana", "banana"]
fruit_count = {}
for fruit in fruits:
fruit_count[fruit] = fruit_count.get(fruit, 0) + 1
print(fruit_count)
Explanation:
Counts how many times each item appears.
20.Using defaultdict
Concept: Simplifies counting.
from collections import defaultdict
words = ["hello", "world", "hello", "python"]
word_count = defaultdict(int)
for word in words:
word_count[word] += 1
print(dict(word_count))
Explanation:
Automatically initializes missing keys with default value
Top comments (0)