Python字典的增删查操作示例

原创 超、凢脫俗 2025-03-17 05:30 7阅读 0赞

在Python中,字典是一种可变容器模型,允许存储任意类型对象的键值对。以下是对字典增删查操作的示例:

  1. 增加键值对:
    ```python
    dict_name = {‘name’: ‘Alice’, ‘age’: 25}

增加键’city’和对应的值’New York’

dict_name[‘city’] = ‘New York’

print(dict_name) # 输出:{‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}

  1. 2. 删除键值对:
  2. ```python
  3. dict_name = {'name': 'Alice', 'age': 25}
  4. # 删除键'city'
  5. if 'city' in dict_name:
  6. del dict_name['city']
  7. print(dict_name) # 输出:{'name': 'Alice', 'age': 25}
  1. 查找特定键的值:
    ```python
    dict_name = {‘name’: ‘Alice’, ‘age’: 25}

查找键’age’

if ‘age’ in dict_name:
print(“Age:”, dict_name[‘age’])) # 输出:Age: 25
else:
print(“Key not found: ‘age’”)) # 输出:Key not found: ‘age’
```

以上就是Python字典增删查操作的示例。

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

发表评论

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

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

相关阅读