【发布时间】:2022-08-17 08:19:35
【问题描述】:
dict_A = {
\'Key A\': Value1,
\'Key B\': Value2
}
dict_B = {
Value1: ValueX,
Value2: ValueY
}
当值键匹配时,如何将 dict_A 中的值替换为 dict_B 中的值?
标签: python dictionary
dict_A = {
\'Key A\': Value1,
\'Key B\': Value2
}
dict_B = {
Value1: ValueX,
Value2: ValueY
}
当值键匹配时,如何将 dict_A 中的值替换为 dict_B 中的值?
标签: python dictionary
dict_A = {k: dict_B.get(v, v) for k, v in dict_A.items()}
【讨论】:
您可以使用dict.get():
dict_A = {"Key A": "Value1", "Key B": "Value2"}
dict_B = {"Value1": "ValueX", "Value2": "ValueY"}
for key, value in dict_A.items():
dict_A[key] = dict_B.get(value, value)
print(dict_A)
印刷:
{'Key A': 'ValueX', 'Key B': 'ValueY'}
【讨论】: