[work] Python - 字典(dict)删除元素

朱雀 2022-04-06 19:18 395阅读 0赞

字典(dict)删除元素, 可以选择两种方式, dict.pop(key)和del dict[key].

  1. # -*- coding: utf-8 -*-
  2. def remove_key(d, key):
  3. r = dict(d)
  4. del r[key]
  5. return r
  6. x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
  7. x.pop(1)
  8. print x
  9. x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
  10. del x[1]
  11. print x
  12. x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
  13. print remove_key(x, 1)
  14. print x
  15. """
  16. 输出:
  17. {0: 0, 2: 1, 3: 4, 4: 3}
  18. {0: 0, 2: 1, 3: 4, 4: 3}
  19. {0: 0, 2: 1, 3: 4, 4: 3}
  20. {0: 0, 1: 2, 2: 1, 3: 4, 4: 3}
  21. """

发表评论

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

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

相关阅读

    相关 pythondict字典

    字典是一系列由键(key)和值(value)配对组成的元素的集合,在 Python3.7+,字典被确定为有序(注意:在 3.6 中,字典有序是一个implementation