I've searched and found this Append a dictionary to a dictionary but that clobbers keys from b
if they exist in a
..
I'd like to essentially recursively append 1 dictionary to another, where:
- keys are unique (obviously, it's a dictionary), but each dictionary is fully represented in the result such that
a.keys()
andb.keys()
are both subsets ofc.keys()
- if the same key is in both dictionaries, the resulting key contains a list of values from both, such that
a[key]
andb[key]
are inc[key]
- the values could be another dictionary, (but nothing deeper than 1 level), in which case the same logic should apply (append values) such that
a[key1][key2]
andb[key1][key2]
are inc[key][key2]
The basic example is where 2 dictionary have keys that don't overlap, and I can accomplish that in multiple ways.. c = {**a, **b}
for example, so I haven't covered that below
A trickier case:
a = {
"key1": "value_a1"
"key2": "value_a2"
}
b = {
"key1": "value_b1"
"key3": "value_b3"
}
c = combine(a, b)
c >> {
"key1": ["value_a1", "value_b1"],
"key2": "value_a2",
"key3": "value_b3"
}
An even trickier case
a = {
"key1": {
"sub_key_1": ["sub_value_a1", "sub_value_a2"],
"sub_key_2": "sub_value_a3"
},
"key2": "value_a2"
}
b = {
"key1": {
"sub_key_1": ["sub_value_a1", "sub_value_b1"],
"sub_key_2": "sub_value_b3"
},
"key3": "value_b3" # I'm okay with converting this to a list even if it's not one
}
c = combine(a, b)
c >> {
"key1": {
"sub_key_1": ["sub_value_a1", "sub_value_a2", "sub_value_b1"], #sub_value_a1 is not duplicated
"sub_key_2": ["sub_value_a3", "sub_value_b3"]
},
"key2": "value_a2",
"key3": "value_b3" # ["value_b3"] this would be okay, following from the code comment above
}
Caveats:
- Python 3.6
- The examples show lists being created as_needed, but I'm okay with every non-dict value being a list, as mentioned in the code comments
- The values within the lists will always be strings
I tried to explain as best I could but can elaborate more if needed. Been working on this for a few days and keep getting stuck on the sub key part