I have the following scenario - consider the list of dictionaries as below (input):
data = [{'key1' : 'k1v1', 'key2': 'k2v1'}, {'key1': 'k1v2', 'key2': 'k2v2'},
{'key1': 'k1v3', 'key2': 'k2v3'}, {'key1': 'k1v4', 'key2': 'k2v4'}]
As can be observed, the keys across the dictionaries are same. So what I want to be able to do is the following (desired output):
{'key1': ['k1v1', 'k1v2', 'k1v3', 'k1v4'], 'key2': ['k2v1', 'k2v2', 'k2v3', 'k2v4']}
To achieve this, I can use the following simple straight forward nested loop:
data_dict = dict()
for d in data:
for k, v in d.items():
if k in data_dict:
data_dict[k].append(v)
else:
data_dict[k] = [v]
The question: Can we do this using dictionary comprehension? In other words, can we append to existing value lists, inside a dictionary comprehension?