Replace value in dictionary by matching another dictionary

Question:

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?

Asked By: Rafał

||

Answers:

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'}
Answered By: Andrej Kesely
dict_A = {k: dict_B.get(v, v) for k, v in dict_A.items()}
Answered By: bobah
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.