Python - Dictionaries
In Python, you can access values in a dictionary using keys. Here's an example:
# Creating a dictionary
student_info = {"Name": "John", "Age": 25, "City": "New York"}
# Accessing values using keys
name = student_info["Name"]
age = student_info["Age"]
city = student_info["City"]
# Displaying the values
print("Name:", name)
print("Age:", age)
print("City:", city)
Output:
Name: John Age: 25 City: New York
get()
method in Python dictionaries.In Python dictionaries, the get()
method is used to retrieve the value associated with a specified key. It allows you to access a key's value without raising an error if the key is not found. Here's an example:
# Creating a dictionary
student_info = {"Name": "John", "Age": 25, "City": "New York"}
# Using get() to retrieve values
name = student_info.get("Name")
grade = student_info.get("Grade", "Not Available")
# Displaying the values
print("Name:", name)
print("Grade:", grade)
Output:
Name: John Grade: Not Available
In the example, the get()
method is used to retrieve the value associated with the key "Name" (which exists) and "Grade" (which doesn't exist). If the key is not found, the method returns a default value, in this case, "Not Available". This prevents the code from raising a KeyError
.
To add a key-value pair to an existing dictionary in Python, you can use the following syntax:
# Existing dictionary
student_info = {"Name": "John", "Age": 25, "City": "New York"}
# Adding a new key-value pair
student_info["Grade"] = "A"
# Displaying the updated dictionary
print(student_info)
Output:
{'Name': 'John', 'Age': 25, 'City': 'New York', 'Grade': 'A'}
In this example, the key-value pair 'Grade': 'A'
is added to the existing dictionary student_info
using square bracket notation. The dictionary is then printed to show the updated content.
update()
method in Python dictionaries.The update()
method in Python dictionaries is used to merge the key-value pairs from one dictionary into another. If the keys already exist in the target dictionary, their values will be updated; otherwise, new key-value pairs will be added. Here is an example:
# Original dictionary
student_info = {"Name": "John", "Age": 25, "City": "New York"}
# Dictionary to be merged
additional_info = {"Grade": "A", "Hobbies": ["Reading", "Coding"]}
# Using update() to merge dictionaries
student_info.update(additional_info)
# Displaying the updated dictionary
print(student_info)
Output:
{'Name': 'John', 'Age': 25, 'City': 'New York', 'Grade': 'A', 'Hobbies': ['Reading', 'Coding']}
In this example, the update()
method is used to merge the content of the additional_info
dictionary into the student_info
dictionary. The result is a dictionary with updated and additional key-value pairs.