Home > Net >  Replace value in dictionary by matching another dictionary
Replace value in dictionary by matching another dictionary

Time:04-16

dict_A = {
    'Key A': Value1,
    'Key B': Value2
}

dict_B = {
    Value1: ValueX,
    Value2: ValueY
}

How can I replace values in dict_A by a value from dict_B when value-key are matched?

CodePudding user response:

dict_A = {k, dict_B.get(v, v) for k, v in dict_A.items()}

CodePudding user response:

You can use 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)

Prints:

{'Key A': 'ValueX', 'Key B': 'ValueY'}
  • Related