017 字典的内置方法

查看

  • dir(dict): 列出 dict 的方法
  • help(dict): 查看开发者对 dict 方法所编写的详细描述文档
    • help(dict.clear) 可以仅查看 clear() 的用法

clear()

  • 释义:删除字典中所有键值对
>>> d = {"one": 1, "two": 2, "three": 3}
>>> d
{'one': 1, 'two': 2, 'three': 3}
>>> d.clear()
>>> d
{}
>>> 

copy()

  • 释义:返回字典的浅拷贝
>>> d1 = {"one": 1, "two": 2, "three": 3}
>>> d2 = d1.copy()
>>> d1
{'one': 1, 'two': 2, 'three': 3}
>>> d2
{'one': 1, 'two': 2, 'three': 3}
>>> id(d1)
1588975994624
>>> id(d2)
1588975994304
>>> d1["one"] = 100
>>> d1
{'one': 100, 'two': 2, 'three': 3}
>>> d2
{'one': 1, 'two': 2, 'three': 3}
>>> 

get(key, default=None)

items()

  • 释义:返回由字典的键值对组成的元组格式
>>> d = {"one": 1, "two": 2, "three": 3}
>>> d.items()
dict_items([('one', 1), ('two', 2), ('three', 3)])
>>> type(d.items())
<class 'dict_items'>
>>> 

keys()

  • 释义:返回一个由字典所有的键组成的结构
>>> d = {"one": 1, "two": 2, "three": 3}
>>> d.keys()
dict_keys(['one', 'two', 'three'])
>>> type(d.keys())
<class 'dict_keys'>
>>> 

pop()

  • 释义
    • 删除指定的键并返回相应的值
    • 键不存在时,如果设置过返回值,则返回该值;否则,抛出 keyError 异常
>>> d = {"one": 1, "two": 2, "three": 3}
>>> d.pop("one")
1
>>> d.pop("four")
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    d.pop("four")
KeyError: 'four'
>>> d.pop("four", "not found")
'not found'
>>> 

popitem()

  • 释义
    • 移除并返回一组键值对(二元组)
    • 如果字典为空,则抛出 keyerror 异常
>>> d = {"one": 1, "two": 2, "three": 3}
>>> d.popitem()
('three', 3)
>>> k, v = d.popitem()
>>> k
'two'
>>> v
2
>>> d.popitem()
('one', 1)
>>> d.popitem()
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    d.popitem()
KeyError: 'popitem(): dictionary is empty'
>>> 

setdefault(key, default=None)

  • 释义
    • 键在字典中时,返回该键对应的值
    • 键不在字典中时,添加一组键值对
      • 若传入了键值,则使用该值
      • 否则,使用默认值 None
>>> d = {"one": 1, "two": 2, "three": 3}
>>> d.setdefault("one")
1
>>> d.setdefault("four")
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': None}
>>> d.setdefault("five", 5)
5
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': None, 'five': 5}
>>> 

update()

  • 释义
    • 形如 d1.update(d2)
    • 意为把 d2key/value 更新到 d1

例1

>>> d1 = {"one": 1, "two": 2, "three": 3}
>>> d2 = {"four": 4}
>>> d1.update(d2)
>>> d1
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> 

例2

>>> d1 = {"one": 1, "two": 2, "three": 3}
>>> d2 = {"one": 100}
>>> d1.update(d2)
>>> d1
{'one': 100, 'two': 2, 'three': 3}
>>> 

例3

>>> d1 = {"one": 1, "two": 2, "three": 3}
>>> d2 = {"two": 2}
>>> d1.update(d2)
>>> d1
{'one': 1, 'two': 2, 'three': 3}
>>> 

values()

  • 释义:与 keys() 相似,返回一个可迭代的结构
>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> d.values()
dict_values([1, 2, 3])
>>> type(d.values())
<class 'dict_values'>
>>> 
原文地址:https://www.cnblogs.com/yorkyu/p/10293151.html