I'm having difficulty working out a dictionary comprehension.
I have a list of dictionaries, where each dictionary contains identical keys with different values:
list_of_dictionaries = [{k1:v1, k2:v2}{k1:v3, k2:v4}{k1:v5, k2:v6}, ...]
I would like to have a single dictionary of lists, where each key has a value which is a list of those values found under that key in the list of dictionaries:
dictionary_of_lists = {k1:[v1,v3,v5], k2:[v2,v4,v6], ...}
At the moment I'm creating this single, consolidated dictionary by manually entering the keys and using a list comprehension to fetch the values:
dictionary_of_lists = {
k1:[i[k1] for i in list_of_dictionaries],
k2:[i[k2] for i in list_of_dictionaries],
...
}
It's not so bad with a few keys, but with over twenty it's looking messy with repeated code. I'm struggling to formulate a dictionary comprehension which would achieve the same result. Something like "for each dictionary in this list, add the values corresponding to each key to a list represented by the same key in another dictionary"? I've tried the dict.update() method, which won't allow me to add the values to a list - it erases and 'updates' the value already there instead.