In this given dictionary defaultdict(dict) type data:
Say this is the dict1
{726: {'X': [3.5, 3.5, 2.0], 'Y': [2.0, 0.0, 0.0], 'chr': [2, 2, 2]}, 128: {'X': [0.5, 4.0, 4.0], 'Y': [4.0, 3.5, 3.5], 'chr': [3, 3, 3]}}
dict2
is
{726: {'sum_X': [8, 0, 2], 'sum_Y': [3, 2, 0]}, 128: {'sum_X': [0.5, 2, 0], 'sum_Y': [5, 3.5, 3]}}
Expected output:
Union_dict =
{726: {'X': [3.5, 3.5, 2.0], 'Y': [2.0, 0.0, 0.0], 'chr': [2, 2, 2], 'sum_X': [8, 0, 2], 'sum_Y': [3, 2, 0]}, 128: {'X': [0.5, 4.0, 4.0], 'Y': [4.0, 3.5, 3.5], 'chr': [3, 3, 3], 'sum_X': [0.5, 2, 0], 'sum_Y': [5, 3.5, 3]}}
Each dict has a unique key
(i.e 726, 128...) and are found in both dictionaries (dict1 and dict2
) but each key in different dictionaries have unique identifier
with list values
. I want to merge these dictionaries using the unique keys, but also want to keep the order of the values inside the list intact and ordered.
I have tried several methods including the extensive method in How to merge two dictionaries in a single expression? explained by Aaron Hall
. I tried to modify the approaches using what I know about dict comprehension
but its failing.
I tried:
1
union_dict = {k: [dict1[i] for i in v] for k, v in dict2.items()}
2
union_dict = defaultdict(dict) for a,b in dict1.items(), dict2.items(): union_dict[dict1].append(dict2)
3
dicts = [dict1, dict2] union_dict = defaultdict(dict) for a,b in dicts: union_dict[k] = tuple(union_dict[k] for d in dicts)
Also, can you give me a comprehensive explanation of several ways to do it and keep the memory footprint low, since my dictionaries are going to be quite big.
Thanks much !