I found the question How do I merge two dictionaries in a single expression (taking union of dictionaries)? where somebody wanted to merge dictionaries as union, but I want to merge dictionaries depending on the same "key" (where I don't know what key exactly) and still keep ALL information. When I tried the answer in the question I got the union but only the values of the 2nd dictionary where kept. That is not what I want. What I want is:
Lets say I have two dictionaries including lists which again includes dicts with different keys
myDict1 = [
{'key1': 'list1'},
{'key2': 'list2'},
{'key3': 'list3'}
]
myDict2 = [
{'key4': 'list4'},
{'key1': 'list5'},
{'key3': 'list6'},
{'key5': 'list7'}
]
now I want to merge the dictionaries where the keys have the same value, e.g., key1
but I don't know what key1
is so i can't use a criteria like =='key1'
.
Resulting in (I use the "union_with_keys_and_values_from_both" to make sure that you understand what I want to achieve)
myMergedDict = [
{'key1': 'union_with_keys_and_values_from_both(list1,list5)'},
{'key2': 'list2'},
{'key3': 'union_with_keys_and_values_from_both(list3,list6)'},
{'key4': 'list7'},
{'key5': 'list8'},
]
So every value of both dictionaries should be kept when merged.
Further remark:
lets say
list1 = (dict1)
list5 = (dict2, dict3)
dict1 = [
{'key1': 'value1'},
{'key2': 'value2'},
{'key3': 'value3'}
]
dict2 = [
{'key4': 'value4'},
{'key2': 'value5'},
{'key5': 'value6'}
]
dict3 = [
{'key6': 'value7'},
{'key4': 'value8'},
{'key7': 'value9'}
]
Then union_with_keys_and_values_from_both(list1,list5) should result in
unionList1List5 = [
{'key1': 'value1'},
{'key2': ('value2', 'value5')},
{'key3': 'value3'}
{'key4': ('value4', 'value8')},
{'key5': 'value6'}
{'key6': 'value7'},
{'key7': 'value9'}
]