目录
1. Python3 中如何查看 dict() 的内置方法
- help(dict()) / help(dict)
- dir(dict()) / dir(dict)
2. 少废话,上例子
(1) 清理大师 clear()
- 释义:删除字典中所有键值对
- 示例:
# 例1
d1 = {"one":1, "two":2, "three":3}
print(d1)
d1.clear()
print(d1)
- 运行结果
{'one': 1, 'two': 2, 'three': 3}
{}
(2) 拷贝君 copy()
- 释义:返回字典的浅拷贝
- 示例:
# 例2
d2_1 = {"one":1, "two":2, "three":3}
d2_2 = d2_1.copy()
print("d2_1 =", d2_1)
print("id(d2_1) =", id(d2_1))
print("d2_2 =", d2_2)
print("id(d2_2) =", id(d2_2))
- 运行结果
d2_1 = {'one': 1, 'two': 2, 'three': 3}
id(d2_1) = 2648942750168
d2_2 = {'one': 1, 'two': 2, 'three': 3}
id(d2_2) = 2648942630160
(3) get(key, default=None)
(4) items()
- 释义:返回由字典的键值对组成的元组格式
- 示例:
# 例3
d3 = {"one":1, "two":2, "three":3}
i3 = d3.items()
print(type(i3))
print(i3)
- 运行结果
<class 'dict_items'>
dict_items([('one', 1), ('two', 2), ('three', 3)])
(5) keys()
- 释义:返回一个由字典所有的键组成的结构
- 示例:
# 例4
d4 = {"one":1, "two":2, "three":3}
k4 = d4.keys()
print(type(k4))
print(k4)
- 运行结果
<class 'dict_keys'>
dict_keys(['one', 'two', 'three'])
(6) pop()
- 释义:
- 删除指定的键并返回相应的值
- 键不存在时,如果设置过返回值,则返回该值;否则,抛出异常 keyError
- 示例:
# 例5.1
d5 = {"one":1, "two":2, "three":3}
p5_1 = d5.pop("one")
p5_2 = d5.pop("four", 4)
print(p5_1)
print(p5_2)
print(d5)
- 运行结果
1
4
{'two': 2, 'three': 3}
# 例5.2
d5 = {"one":1, "two":2, "three":3}
p5_3 = d5.pop("ten")
- 运行结果
KeyError……'ten'
(7) popitem()
- 释义:
- 移除并返回一些(键、值)对作为2元组
- 如果d为空,则引发keyror。
- 示例:
# 例6.1
d6_1 = {"one":1, "two":2, "three":3}
p6 = d6_1.popitem()
print(p6_1)
key, value = d6_1.popitem()
print(key, "<-->", value)
- 运行结果
('three', 3)
two <--> 2
# 例6.2
d6_2 = {}
print(d6_2.popitem())
- 运行结果
KeyError: 'popitem(): dictionary is empty'
(8) setdefault(key, default=None)
- 释义:
- 键在字典中时,则返回该键对应的值
- 键不在字典中时,添加一组键值对,键为传入的键值;若传入了值,则值为该值,否则,值为默认值 None
- 示例:
# 例7
d7 = {"one":1, "two":2, "three":3}
print(d7.setdefault("one"))
print(d7.setdefault("four"))
print(d7)
print(d7.setdefault("five", 5))
print(d7)
- 运行结果
1
None
{'one': 1, 'two': 2, 'three': 3, 'four': None}
5
{'one': 1, 'two': 2, 'three': 3, 'four': None, 'five': 5}
(9) update()
- 释义:
- 形如 dict1.update(dict2)
- 把字典 dict2 的 key/value 更新到字典 dict1 里
- 示例:
# 例8.1
dict8_1 = {"one":1, "two":2, "three":3}
dict8_2 = {"four":4}
dict8_1.update(dict8_2)
print ("new dict:", dict8_1)
- 运行结果
new dict: {'one': 1, 'two': 2, 'three': 3, 'four': 4}
# 例8.2
dict8_3 = {"one":1, "two":2, "three":3}
dict8_4 = {"two":2}
dict8_3.update(dict8_4) # 想更新的键值对为重复键值对
print ("new dict:", dict8_3)
- 运行结果
new dict: {'one': 1, 'two': 2, 'three': 3}
(10) values()
- 释义:与 keys() 相似,返回一个可迭代的结构
- 示例:
# 例9
d9 = {"one":1, "two":2, "three":3}
v9 = d9.values()
print(type(v9))
print(v9)
- 运行结果
<class 'dict_values'>
dict_values([1, 2, 3])