通过匹配另一个字典替换字典中的值
Replace value in dictionary by matching another dictionary
dict_A = {
'Key A': Value1,
'Key B': Value2
}
dict_B = {
Value1: ValueX,
Value2: ValueY
}
当值键匹配时,如何用 dict_B 中的值替换 dict_A 中的值?
您可以使用 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'}
dict_A = {k, dict_B.get(v, v) for k, v in dict_A.items()}
dict_A = {
'Key A': Value1,
'Key B': Value2
}
dict_B = {
Value1: ValueX,
Value2: ValueY
}
当值键匹配时,如何用 dict_B 中的值替换 dict_A 中的值?
您可以使用 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'}
dict_A = {k, dict_B.get(v, v) for k, v in dict_A.items()}