python字典合并

# 合并字典
dic_a = {"user": "aa", "pwd": "123"}
dic_b = {"age": 12, "sex": "男"}
# 1.update方法
# dic_a.update(dic_b)
# print(dic_a)

# 2.字典解包
# dic_new = {**dic_a, **dic_b}
# print(dic_new)

# 3.联合字典的方式(3.9才支持)
# dic_new = dic_b | dic_a
# print(dic_new)

# 4.遍历字典,将两个字典组装成列表然后循环遍历
# dic_new = {}
# for _ in [dic_a, dic_b]:
# for key, value in _.items():
# dic_new[key] = value
# print(dic_new)

# 5.第4种方式还可以换成推导式的方式(字典推导式)
new_dic = {key: value for _ in [dic_a, dic_b] for key, value in _.items()}
print(new_dic)
posted @ 2023-03-29 12:53  dyjnicole  阅读(27)  评论(0编辑  收藏  举报