如何在Python中使用字典的键值对操作
在Python中,字典是一种可变容器模型,用于存储和检索数据。你可以通过以下几种方式来操作字典的键值对:
直接赋值:
# 创建一个空字典
dict_example = {}
# 使用键值对直接赋值
dict_example['key1'] = 'value1'
dict_example['key2'] = 42
print(dict_example) # 输出: {'key1': 'value1', 'key2': 42}
通过键获取值:
value1 = dict_example.get('key1')
if value1 is not None:
print(f"Value of key1 is: {value1}")
更新或添加新的键值对:
dict_example.update({'new_key': 'new_value'}) # 添加新的键值对
dict_example['key2'] = 'updated value' # 更新原有的键值对
print(dict_example) # 输出: {'key1': 'value1', 'new_key': 'new_value', 'key2': 'updated value'}
通过这些方式,你可以方便地在Python字典中进行键值对操作。
还没有评论,来说两句吧...