Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Combine dictionaries with common and nonexistent keys without filling the gaps

$
0
0

Here is a list of dictionaries:

dictionaries = [    {"Key 1": "value1""Key 2": "value2""Key 3": "value3"    },    {"Key 1": "value4""Key 3": "value5""Key 4": "value6"    },    {"Key 1": "value7""Key 2": "value8""Key 4": "value9"    }]

Here are my expected results:

mergedDictionaries = {"Key 1": ["value1", "value4", "value7"],"Key 2": ["value2", "", "value8"],"Key 3": ["value3", "value5", ""],"Key 4": ["", "value6", "value9"]}

I tried using the collections module, but it fills up the gaps using this code below.

dictionary = defaultdict(list)for key in dictionaries:    for x, y in key.items():        dictionary[x].append(y)

The whole point of this is to make an accurate dataframe when combining the dictionaries.

Is there any method to recreate this situation?


Viewing all articles
Browse latest Browse all 23131

Trending Articles