需求
:A和B是两个字典,Key值存在相同的值,当两个字典的key值相同的时候,如何将dic1对应的values取出来作为新的字典values,dic2对应的values取出来作为新字典的key
A = {"name": "姓名", "age": "年龄", "gender": "性别"}
B = {"name": "小明", "age": 18, "gender": "男"}
# 方法一:
sub = {A[x]: B[x] for x in B if x in A}
print(sub)
{'姓名': '小明', '年龄': 18, '性别': '男'}
# 方法二:
for key, value in A.items():
for k in B.keys():
if key == k:
# 需要转dict不然会报错
# AttributeError: 'str' object has no attribute 'keys'
B = eval(str(B).replace(k, value))
print(B)
{'姓名': '小明', '年龄': 18, '性别': '男'}
# 方法三:
# 遍历其中一个字典的Key,然后替换
for key in B.keys():
A[key] = B[key]
print(B)
{'姓名': '小明', '年龄': 18, '性别': '男'}