Index
Dictionaries in Python
Nested Dictionaries
Dictionary Methods in Python
1. Dictionaries in Python
Definition:
A dictionary in Python is an unordered collection of items. Each item in a dictionary is stored as a key-value pair, where the key is a unique identifier, and the value is the data associated with that key. Dictionaries are mutable, meaning you can change their content after creation.
Syntax:
dictionary_name = { key1: value1, key2: value2, key3: value3 }
Explanation:
Dictionaries are highly efficient for retrieving data when you know the key. They are commonly used for situations where you need a logical association between a pair of information, such as storing a person’s name and their corresponding phone number.
Basic Example:
# Creating a simple dictionary
student = {
"name": "Vishal",
"age": 25,
"course": "Data Science"
}
print(student["name"])
# Output: Vishal
Advanced Example:
# Updating and adding elements to the dictionary
student["age"] = 26 # Updating the value of age
student["grade"] = "A+" # Adding a new key-value pair
print(student)
Output:{'name': 'Vishal', 'age': 26, 'course': 'Data Science', 'grade': 'A+'}
Rules/Exceptions:
Keys must be immutable types (e.g., strings, numbers, or tuples).
Keys within a dictionary must be unique; duplications will result in the latter value overwriting the former.
2. Nested Dictionaries
Definition:
A nested dictionary is a dictionary that contains one or more dictionaries as values. This allows for hierarchical data storage, making it easier to organize complex datasets.
Syntax:
nested_dict = { key1: { subkey1: value1, subkey2: value2 }, key2: { subkey1: value1, subkey2: value2 } }
Explanation:
Nested dictionaries are useful when dealing with multi-level data. For example, in a database storing student records, each student could be a key, and their details (such as age, course, and grades) could be another dictionary as the value.
Basic Example:
# Creating a nested dictionary
students = {
"student1": { "name": "Vishal", "age": 25 },
"student2": { "name": "Raj", "age": 24 } }
print(students["student1"]["name"])
# Output: Vishal
Advanced Example:
# Adding a new nested dictionary
students["student3"] = { "name": "Amit", "age": 23 }
print(students)
Output:{'student1': {'name': 'Vishal', 'age': 25}, 'student2': {'name': 'Raj', 'age': 24}, 'student3': {'name': 'Amit', 'age': 23}}
Rules/Exceptions:
The structure can get complex, so it’s essential to manage the nested dictionaries carefully to avoid confusion.
Accessing deeply nested keys should be done with caution to prevent errors like
KeyError
.
3. Dictionary Methods in Python
Definition:
Dictionary methods are built-in functions that can be used to manipulate and interact with dictionaries. These methods allow for adding, updating, removing items, and more.
Explanation:
Some commonly used dictionary methods include:
get()
: Returns the value for a specified key.keys()
: Returns a list of all the keys in the dictionary.values()
: Returns a list of all the values in the dictionary.items()
: Returns a list of key-value pairs.update()
: Updates the dictionary with elements from another dictionary or from an iterable of key-value pairs.pop()
: Removes the specified key and returns the corresponding value.clear()
: Removes all items from the dictionary.
Basic Example:
# Using the get() method
student = {"name": "Vishal", "age": 25}
age = student.get("age")
print(age)
# Output: 25
Advanced Example:
# Using update() and pop() methods
student.update({"course": "Data Science"})
grade = student.pop("age")
print(student)
# Output: {'name': 'Vishal', 'course': 'Data Science'}
print(f"Removed age: {grade}")
# Output: Removed age: 25
Rules/Exceptions:
Using
pop()
on a non-existent key will raise aKeyError
. To avoid this, you can provide a default value as a second argument topop()
.The
update()
method overwrites existing keys but does not alter keys that are not in the provided dictionary or iterable.
Conclusion
In this edition of FM University, we've explored the core concepts of Python dictionaries, including basic dictionaries, nested dictionaries, and the essential methods to manage them. Mastering dictionaries will empower you to handle complex data structures efficiently, making your Python programming more effective.
- Vishal Rajput