'Replace value in dictionary by matching another dictionary
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?
Solution 1:[1]
dict_A = {k, dict_B.get(v, v) for k, v in dict_A.items()}
Solution 2:[2]
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'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bobah |
| Solution 2 | Andrej Kesely |
