Python字典操作:查找,更新与删除示例

原创 傷城~ 2025-02-01 06:39 55阅读 0赞

在Python中,字典是一种可变容器模型,类似于现实生活中使用的各种盒子。字典的每个键值对用冒号 : 分割,每对键值对之间用逗号 , 分割。

以下是一些查找、更新和删除字典内容的示例:

  1. 查找:
    ```python

    创建一个字典

    dict = {‘name’: ‘John’, ‘age’: 30}

查找键为’name’的值

value = dict.get(‘name’)
print(value) # 输出: John

如果键不存在,get()方法将返回None

value = dict.get(‘city’) # 假设 city 在字典中
print(value) # 输出: None

  1. 2. 更新:
  2. ```python
  3. dict = {'name': 'John', 'age': 30}
  4. # 使用update()方法更新字典
  5. dict.update({'address': '123 Main St'}})
  6. print(dict)
  7. # 输出:
  8. # {'name': 'John', 'age': 30, 'address': '123 Main St'}
  1. 删除:
    ```python
    dict = {‘name’: ‘John’, ‘age’: 30}

使用pop()方法删除并返回指定的键值对,如果键不存在,则返回None和None

value = dict.pop(‘age’)

if value is not None:
print(“Deleted age: “, value)
else:
print(“Key ‘age’ not found in dictionary.”)

```
以上就是Python字典操作的一些基本示例。

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

发表评论

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

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

相关阅读