Python字典学习:创建、修改和查询字典
在Python中,字典是一种可变容器模型,它通过键(Key)来存储值(Value)。以下是关于创建、修改和查询字典的一些基本操作:
创建包含多个键值对的字典
my_dict = {
‘name’: ‘John Doe’,
‘age’: 30,
‘city’: ‘New York’
}
print(“Empty dictionary:”, empty_dict)
print(“My dictionary:”, my_dict)
2. 修改字典:
```python
# 更新键值对
my_dict['age'] = 31
# 如果键不存在,会添加新的键值对
if 'country' not in my_dict:
my_dict['country'] = 'USA'
print("Updated dictionary:", my_dict)
print(f”The value of ‘age’ is: {value_of_key}”)
判断字典中是否存在某个键
contains_key = ‘name’ in my_dict
print(f”Does the dictionary contain ‘name’? {contains_key}”)
```
总结一下,Python中的字典是一种强大的数据结构,用于存储和操作键值对。通过创建、修改和查询字典,我们可以方便地处理各种数据问题。
还没有评论,来说两句吧...