- Create a dictionary named student and print it student = { "name": "Alice", "age": 21, "major": "Computer Science" }
print(student)
Explanation:
A dictionary stores data in key-value pairs.
Keys must be unique.
Values can be of any data type.
- Print the values of "name" and "major" print("Name:", student["name"]) print("Major:", student["major"])
Explanation:
Use square brackets [] with the key to access values.
- Add "gpa" and update "age" student["gpa"] = 3.8 student["age"] = 22
print(student)
Explanation:
Assigning a new key adds it.
Assigning an existing key updates it.
- Remove the key "major" using del del student["major"] print(student)
Explanation:
del removes a specific key-value pair.
- Check if "age" exists print("age" in student)
Explanation:
The in operator checks if a key exists.
Returns True or False.
- Create prices dictionary and iterate prices = { "apple": 0.5, "banana": 0.3, "orange": 0.7 }
for item, price in prices.items():
print(item, ":", price)
Explanation:
items() returns key-value pairs.
Looping allows us to access both.
- Find number of key-value pairs print("Number of items:", len(prices))
Explanation:
len() returns total entries in the dictionary.
- Use get() method print("GPA:", student.get("gpa")) print("Graduation Year:", student.get("graduation_year", 2025))
Explanation:
get() avoids errors if key does not exist.
Default value is returned if key is missing.
- Merge another dictionary using update() extra_info = { "graduation_year": 2025, "hometown": "Springfield" }
student.update(extra_info)
print(student)
Explanation:
update() merges two dictionaries.
Existing keys are updated; new keys are added.
- Dictionary comprehension (Squares) squares = {num: num**2 for num in range(1, 6)} print(squares)
Explanation:
Dictionary comprehension creates dictionaries dynamically.
Keys are numbers 1 to 5.
Values are their squares.
- Print keys and values separately print("Keys:", list(prices.keys())) print("Values:", list(prices.values()))
Explanation:
keys() returns all keys.
values() returns all values.
Convert to list for better display.
- Nested dictionary and access value school = { "student1": {"name": "Alice", "age": 21}, "student2": {"name": "Bob", "age": 22} }
print("Age of student2:", school["student2"]["age"])
Explanation:
Access nested dictionary using multiple keys.
- Use setdefault() student.setdefault("advisor", "Dr. Smith") print(student)
Explanation:
Adds key only if it does not already exist.
- Use pop() to remove "hometown" hometown_value = student.pop("hometown") print("Removed hometown:", hometown_value)
Explanation:
pop() removes key and returns its value.
- Clear the prices dictionary prices.clear() print(prices)
Explanation:
clear() removes all key-value pairs.
- Copy dictionary and modify copy student_copy = student.copy() student_copy["name"] = "Charlie"
print("Original:", student)
print("Copy:", student_copy)
Explanation:
copy() creates a shallow copy.
Modifying the copy does not affect original.
- Create dictionary using zip() keys = ["name", "age", "major"] values = ["Eve", 20, "Mathematics"]
new_student = dict(zip(keys, values))
print(new_student)
Explanation:
zip() pairs elements from two lists.
dict() converts them into a dictionary.
- Iterate using items() for key, value in student.items(): print(key, ":", value)
Explanation:
items() allows iteration over key-value pairs.
- Count occurrences of fruits fruits = ["apple", "banana", "apple", "orange", "banana", "banana"]
fruit_count = {}
for fruit in fruits:
if fruit in fruit_count:
fruit_count[fruit] += 1
else:
fruit_count[fruit] = 1
print(fruit_count)
Explanation:
If fruit exists, increment count.
Otherwise, initialize it to 1.
- Using collections.defaultdict 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:
defaultdict(int) automatically initializes missing keys to 0.
Simplifies counting logic.
Top comments (0)