Dictionaries are an essential data structure in Python that allow us to store and manipulate data using key-value pairs. In dictionaries, the keys are unique and the values can be any data type, making them very versatile and useful for a wide range of applications. In this article, we will explore how to access and modify dictionaries using key-value pairs in Python.
Key-Value Pairs: Accessing Dictionaries in Python
Dictionaries are defined using curly braces {} and key-value pairs separated by a colon :. For example, to create a dictionary of fruits and their prices, we can use the following code:
fruits = {"apple": 1.0, "banana": 0.5, "orange": 0.8}
To access the value of a specific key, we can use the square bracket notation with the key inside, like this:
print(fruits["apple"]) # Output: 1.0
We can also use the get() method of the dictionary to access the value of a key. This method returns None if the key is not found, or a default value if provided:
print(fruits.get("watermelon")) # Output: None
print(fruits.get("watermelon", 2.0)) # Output: 2.0
Learn to Access and Modify Dictionaries with Python
To add a new key-value pair to a dictionary, we can use the square bracket notation with the new key and assign it a value:
fruits["grape"] = 1.2
print(fruits) # Output: {"apple": 1.0, "banana": 0.5, "orange": 0.8, "grape": 1.2}
To modify the value of an existing key, we can use the same notation with the existing key:
fruits["banana"] = 0.7
print(fruits) # Output: {"apple": 1.0, "banana": 0.7, "orange": 0.8, "grape": 1.2}
To remove a key-value pair from a dictionary, we can use the del keyword with the key inside:
del fruits["orange"]
print(fruits) # Output: {"apple": 1.0, "banana": 0.7, "grape": 1.2}
Mastering Key-Value Pairs in Dictionaries with Python
Dictionaries can also be nested, meaning that the values of a dictionary can be dictionaries themselves. To access a value in a nested dictionary, we can use the square bracket notation multiple times with each key:
market = {"fruits": {"apple": 1.0, "banana": 0.5, "orange": 0.8}, "vegetables": {"carrot": 0.3, "potato": 0.4}}
print(market["fruits"]["banana"]) # Output: 0.5
We can also use loops to iterate over the keys or values of a dictionary:
for key in fruits:
print(key) # Output: "apple", "banana", "grape"
for value in fruits.values():
print(value) # Output: 1.0, 0.7, 1.2
for key, value in fruits.items():
print(key, value) # Output: "apple" 1.0, "banana" 0.7, "grape" 1.2
OUTRO:
In this article, we have learned the basics of accessing and modifying dictionaries using key-value pairs in Python. Dictionaries are a powerful tool for storing and manipulating data, and mastering key-value pairs can open up a whole world of possibilities for your programming projects. With some practice and experimentation, you can become a master of dictionaries in Python.