深入解析Python字典的增删查操作

原创 缺乏、安全感 2025-01-17 13:09 55阅读 0赞

在Python中,字典是一种可变容器模型,且可存储任意类型对象。字典的增删查操作如下:

  1. 增(add item):

    • 字典使用update()方法添加新键值对,或者直接用键来设置值。
      ```python

      添加一个键值对

      dict = {“name”: “John”, “age”: 30}
      dict[“job”] = “Engineer”
      print(dict) # 输出:{‘name’: ‘John’, ‘age’: 30, ‘job’: ‘Engineer’}

    或者用直接键来设置值

    dict[“address”] = “123 Main St”
    print(dict) # 输出:{‘name’: ‘John’, ‘age’: 30, ‘job’: ‘Engineer’, ‘address’: ‘123 Main St’}
    ```

  2. 删(remove item):

    • 使用del关键字删除键值对,或者使用pop()方法删除并返回指定的键对应的值。
      ```python

      删除键值对

      dict = {“name”: “John”, “age”: 30}
      del dict[“age”]
      print(dict) # 输出:{‘name’: ‘John’, ‘age’: None}

    使用pop()方法删除并返回指定键的值

    job = dict.pop(“job”)
    print(job, dict) # 输出:”Engineer” ({‘name’: ‘John’, ‘age’: 30, ‘job’: None}})
    ```

  3. 查(search for key):

    • 使用in关键字检查键是否存在于字典中。
      ```python
      dict = {“name”: “John”, “age”: 30}
      print(“Age” in dict) # 输出:True

    job = “Engineer”
    if job in dict:

    1. print(f"{job}" is present in the dictionary))

    else:

    1. print(f"{job}" is not present in the dictionary"))

    ```

这就是Python字典的增删查操作。

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

发表评论

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

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

相关阅读