Python IDE: https://www.programiz.com/python-programming/online-compiler/
1. Introduction to Dictionaries
What is a Dictionary?
- A dictionary in Python is a collection of key-value pairs.
- Each key is unique, and maps to a specific value.
- Dictionaries are unordered (until Python 3.7) and mutable (modifiable).
- Syntax:
{key1: value1, key2: value2, ...}.
Creating a Dictionary
# Empty dictionary
empty_dict = {}
# Dictionary with some initial key-value pairs
student = {
"name": "Alice",
"age": 22,
"major": "Physics"
}
print(student)
Output:
{'name': 'Alice', 'age': 22, 'major': 'Physics'}
2. Basic Operations with Dictionaries
Accessing Values
- Access values using keys inside square brackets or with
get(). get()allows a default value if the key doesn’t exist.
print(student["name"]) # Output: Alice
print(student.get("age")) # Output: 22
print(student.get("GPA", "Not available")) # Output: Not available
Adding or Updating Values
- Add new key-value pairs or update existing keys.
student["GPA"] = 3.8 # Add new key-value
student["major"] = "Mathematics" # Update existing key
print(student)
Deleting Key-Value Pairs
- Use
delorpop()to remove a key-value pair.
del student["age"]
print(student) # 'age' key is removed
# Using pop() to remove and return a value
gpa = student.pop("GPA", "No GPA available")
print(gpa) # Output: 3.8
print(student)
3. Dictionary Methods
Common Dictionary Methods
keys(): Returns a view object of all keys.values(): Returns a view object of all values.items(): Returns key-value pairs as tuples in a view object.
print(student.keys()) # Output: dict_keys(['name', 'major'])
print(student.values()) # Output: dict_values(['Alice', 'Mathematics'])
print(student.items()) # Output: dict_items([('name', 'Alice'), ('major', 'Mathematics')])
Checking for a Key
- Use the
inkeyword to check if a key exists.
print("name" in student) # Output: True
print("age" in student) # Output: False
4. Iterating Over Dictionaries
Looping through Keys
for key in student:
print(key, student[key])
Looping through Key-Value Pairs
for key, value in student.items():
print(f"{key}: {value}")
5. Practical Examples
Example 1: Counting Word Frequency
text = "python is easy and fun to learn and python is powerful"
word_count = {}
for word in text.split():
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
Example 2: Storing Nested Data
- Dictionaries can hold complex data, like lists or other dictionaries.
student_profiles = {
"Alice": {"age": 22, "major": "Physics"},
"Bob": {"age": 20, "major": "Mathematics"}
}
print(student_profiles["Alice"]["major"]) # Output: Physics
6. Advanced Features
Dictionary Comprehensions
- Similar to list comprehensions, dictionary comprehensions provide a concise way to create dictionaries.
squares = {x: x*x for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Merging Dictionaries
- Python 3.9 introduced a new way to merge dictionaries with the
|operator.
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2
print(merged) # Output: {'a': 1, 'b': 3, 'c': 4}
7. Conclusion and Practice
Dictionaries are powerful for managing and organizing data in key-value pairs. Practice these examples, and try using dictionaries in small projects, like organizing data or counting occurrences in text.
This tutorial covers the fundamentals of using dictionaries in Python and provides practical examples for hands-on practice.
