Python字典操作:添加、更新及删除案例

原创 叁歲伎倆 2025-02-21 08:06 36阅读 0赞

在Python中,字典是一种可变容器模型,它通过键值对来存储数据。以下是一些关于添加、更新和删除字典元素的案例:

  1. 添加新键值对
  1. dict_obj = {'Name': 'John', 'Age': 30}
  2. # 添加新键'City'及其值'New York'
  3. dict_obj['City'] = 'New York'
  4. print(dict_obj) # 输出: {'Name': 'John', 'Age': 30, 'City': 'New York'}
  1. 更新已有键的值
  1. dict_obj = {'Name': 'John', 'Age': 30}
  2. # 更新'Age'为新的值45
  3. dict_obj['Age'] = 45
  4. print(dict_obj) # 输出: {'Name': 'John', 'Age': 45, 'City': None}
  1. 删除键值对(如果键存在)
  1. dict_obj = {'Name': 'John', 'Age': 30}
  2. # 删除键'Age'
  3. if 'Age' in dict_obj:
  4. del dict_obj['Age']
  5. print(dict_obj) # 输出: {'Name': 'John', 'Age': None, 'City': None}

以上案例展示了Python字典的增删改操作。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,36人围观)

还没有评论,来说两句吧...

相关阅读