The code below works. The question is if there is a better and more elegant (maintainable) way.
The task is to update a Python dictionary which values are lists with another dictionary with the same structure (values are lists). The usual dict.update()
doesn't work because values (the lists) are replaced not updated (via list.extend()
).
Example:
a = {'A': [1, 2], 'C': [5]}
b = {'X': [8], 'A': [7, 921]}
Using dict.update()
would result in
{'A': [7, 921], 'C': [5], 'X': [8]}
But A
should become [1, 2, 7, 921]
.
Here is my working solution:
#!/usr/bin/env python3
from typing import Any
def update_dict_with_list_values(
a: dict[Any,list], b: dict[Any,list]) -> dict[Any,list]:
"""Update a dictionary and its list values from another dict."""
# create a local deep copy
a = a.copy()
for key in a:
try:
# remove the list
b_value = b.pop(key)
except KeyError:
pass
else:
# extend the list
a[key] = a[key] + b_value
# add the rest of keys that are not present in the dict to update
a.update(b)
return a
if __name__ == '__main__':
a = {
'A': [1, 2],
'C': [5]
}
b = {
'X': [8],
'A': [7, 921]
}
c = update_dict_with_list_values(a, b)
print(c) # -> {'A': [1, 2, 7, 921], 'C': [5], 'X': [8]}