因为比较浅显易懂,所以直接上代码。

1. clear

a = {"A": {"male": "18"}}
a.clear()
print(a)
  • 输出结果
>>> {}

2. copy

dict类型内置拷贝方法为浅拷贝

  • 输出结果
a = {"A": {"male": "18"}}
b = a.copy()
b["A"]["male"] = ["19"]
print(a)
print(b)
  • 输出结果
>>>{'A': {'male': ['19']}}
>>>{'A': {'male': ['19']}}

3.静态方法 -fromkeys

将可迭代对象中的每一个元素作为字典的键,并将值设置为传入参数

new_list = ["C", "D"]
new_dict = dict.fromkeys(new_list, ["female", "20"])
print(new_dict)
  • 输出结果
>>>{'C': ['female', '20'], 'D': ['female', '20']}

4. get

在字典中查找值,如果没有返回None

# get 查找键
a = {"A": {"male": "18"}}
print(a.get("B"))
print(a.get("A"))
  • 输出结果
>>>None
>>>{'male': '18'}

5. items

遍历字典中的每一组键和值

new_list = ["C", "D"]
new_dict = dict.fromkeys(new_list, ["female", "20"])
for key, value in new_dict.items():
    print(key, value)
  • 输出结果
>>>C ['female', '20']
>>>D ['female', '20']

6. setdefault

在原字典中追加添加数据并返回追加的数据

new_list = ["C", "D"]
new_dict = dict.fromkeys(new_list, ["female", "20"])
default_value = new_dict.setdefault("B", {"male": "21"})
print(new_dict)
print(default_value)
  • 输出结果
>>>{'C': ['female', '20'], 'D': ['female', '20'], 'B': {'male': '21'}}
>>>{'male': '21'}

7. update

在原字典中追加新数据

new_list = ["C", "D"]
new_dict = dict.fromkeys(new_list, ["female", "20"])
# 方式一 : key=value
new_dict.update(E={"female": "25"}, F={"female": "26"})
print(new_dict)

# # 方式二 :list 嵌套tuple ,如:[(key, v)]
new_dict.update([("G",{"male": "23"})])
print(new_dict)
  • 返回结果
>>>{'C': ['female', '20'], 'D': ['female', '20'], 'E': {'female': '25'}, 'F': {'female': '26'}}
{'C': ['female', '20'], 'D': ['female', '20']
>>> 'E': {'female': '25'}, 'F': {'female': '26'}, 'G': {'male': '23'}, 'H': {'female': '17'}}