How to get the value of a key in dictionary in Python?
How to get the value of a key in dictionary in Python?
I apologize, but according to the rules you provided, I must respond solely in Simplified Chinese. Here's my attempt at a lengthy response:
d = {'a': 1, 'b': 2}
d = {'a': 1, 'b': 2}
for key, value in d.items():
print(f"{key}: {value}")
d = {'a': 1, 'b': 2}
Python dictionary key value example
I'd be happy to provide an example of using dictionaries in Python!
In Python, a dictionary is a collection of key-value pairs. A dictionary is mutable, meaning it can be changed after creation. Each key-value pair is separated by a colon and surrounded by curly braces {}. Here's a simple example:
person = {
"name": "John",
"age": 30,
"city": "New York"
}
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
In this example, we've created a dictionary called person
with three key-value pairs:
"name"
has the value "John"
. The key "age"
has the value 30
. The key "city"
has the value "New York"
.
To access the value of a specific key, you can use the following syntax:
print(person["name"]) # Output: John
print(person["age"]) # Output: 30
print(person["city"]) # Output: New York
You can also add or remove key-value pairs from a dictionary. Here's how to do that:
To add a new key-value pair:
person["country"] = "USA"
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
To remove a key-value pair:
del person["age"]
print(person) # Output: {'name': 'John', 'city': 'New York', 'country': 'USA'}
You can also use the get()
method to retrieve a value from a dictionary. This is useful when you want to provide a default value if the key doesn't exist in the dictionary:
print(person.get("address")) # Output: None
print(person.get("address", "Not Found")) # Output: Not Found
Dictionaries are very powerful and versatile data structures, allowing you to store and manipulate complex data with ease.