I need help converting these dictionaries to a single dictionary. See below
data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]
I want to convert it to below:
{'x':[3,5,1], 'y':[3,3,4]
thank you!
I need help converting these dictionaries to a single dictionary. See below
data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]
I want to convert it to below:
{'x':[3,5,1], 'y':[3,3,4]
thank you!
You can use a dictionary comprehension:
data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]
new_data = {i:[c.get(i) for c in data] for i in ['x', 'y']}
Output:
{'y': [3, 3, 4], 'x': [3, 5, 1]}
However, to be more generic, you can use reduce
:
from functools import reduce
new_result = {
i : [c.get(i) for c in data]
for i in set(reduce(
lambda x, y:list(getattr(x, 'keys', lambda :x)()) + list(y.keys()), data)
)
}
Edit: shorter generic solution:
new_s = {i for b in map(dict.keys, data) for i in b}
new_data = {i:[c.get(i) for c in data] for i in new_s}
Here is an easy way to do it:
data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]
emptyX = []
emptyY = []
for i in data:
emptyX.append(i['x'])
emptyY.append(i['y'])
final = {'x':emptyX, 'y':emptyY}
print(final)
Here you just create two empty lists. One to store the x
values and one to store the y
values and then add the value of each dictionary while the for
loop initerates through the list.