Python字典理解挑战:如何在字典中查找、添加和删除值?
在Python字典中,你可以通过键(key)来查找、添加和删除值。以下是一些示例:
- 查找值:
my_dict = {'name': 'John', 'age': 30}
value_to_find = 'name'
if value_to_find in my_dict:
print("Found:", my_dict[value_to_find]])
else:
print("Value not found.")
- 添加值:
```python
my_dict = {‘name’: ‘John’, ‘age’: 30}
new_value = ‘location’: ‘New York’
my_dict.update(new_value)
print(“Updated Dictionary:”)
for key, value in my_dict.items():
print(f”{key}: {value}”)
3. 删除值:
```python
my_dict = {'name': 'John', 'age': 30, 'address': '123 Main St'}
# 删除键值对
if 'address' in my_dict:
del my_dict['address']
print("Updated Dictionary:")
for key, value in my_dict.items():
print(f"{key}: {value}")
以上就是在Python字典中查找、添加和删除值的方法。
还没有评论,来说两句吧...