Dictionaries are versatile data structures in Python used to store key-value pairs. They allow you to efficiently retrieve and manipulate data based on keys. In this topic, we'll explore everything you need to know about dictionaries, from basic operations to advanced techniques.
A dictionary is a collection of key-value pairs, where each key is associated with a value. Dictionaries are unordered and mutable.
To create a dictionary in Python, enclose key-value pairs within curly braces {}
.
# Example of creating a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
You can access values in a dictionary using keys.
# Example of accessing elements in a dictionary
print(my_dict["name"]) # Output: Alice
print(my_dict["age"]) # Output: 30
You can add new key-value pairs to a dictionary or update existing values using assignment.
# Example of adding and updating elements in a dictionary
my_dict["email"] = "alice@example.com" # Adding a new key-value pair
my_dict["age"] = 31 # Updating an existing value
print(my_dict)
You can remove elements from a set using methods like remove()
or discard()
.
# Example of removing elements from a dictionary
del my_dict["city"] # Using del keyword
removed_age = my_dict.pop("age") # Using pop() method
print(removed_age)
print(my_dict)
Dictionaries support various operations like checking if a key exists, getting the number of key-value pairs, and iterating over keys, values, or items.
# Example of dictionary operations
print("name" in my_dict) # Check if key exists
print(len(my_dict)) # Get the number of key-value pairs
for key in my_dict: # Iterate over keys
print(key)
for value in my_dict.values(): # Iterate over values
print(value)
for key, value in my_dict.items(): # Iterate over items
print(key, value)
Similar to list comprehensions, dictionary comprehensions provide a concise way to create dictionaries based on existing iterables.
# Example of dictionary comprehension
squared_numbers = {x: x ** 2 for x in range(1, 6)}
print(squared_numbers)
You can set default values for keys in dictionaries using the get()
method or the setdefault()
method.
# Example of default values in dictionaries
print(my_dict.get("name", "Unknown")) # Using get() method
print(my_dict.setdefault("email", "Not available")) # Using setdefault() method
=
Dictionaries are powerful and flexible data structures in Python, offering efficient storage and retrieval of key-value pairs. By understanding the basics of dictionaries, including creation, accessing elements, and common operations like adding, updating, and removing elements, you can effectively work with structured data in your Python programs. Additionally, exploring advanced techniques like dictionary comprehensions and default values enhances your ability to manipulate dictionaries in various scenarios. Remember to leverage dictionaries where key-value mapping is required and practice using them to solve problems and optimize your code. Happy Coding!❤️