I have the data
data = [{'name': 'Dave', 'role': 'Manager'}, {'name': 'David', 'role': 'Engineer'}]
I am intending to add the values based on same keys and merging it by semicolon. Expected output is like this as follows
{'name': 'Dave;David', 'role': 'Manager;Engineer'}
What I am trying to do is to convert into matrix then adding all the elements based on the index but it is very tedious approach.
result = [[i[e] for e in sorted(i.keys())] for i in data]
print(result)
current output: [['Dave', 'Manager'], ['David', 'Engineer']]
CodePudding user response:
The following does what you want, assuming that data always contains dictionaries of strings.
I'm checking if each dictionary key already exists in the final dictionary. If it doesn't I add it, if it does I append it to the current value using the semicolon as a separator.
data = [{'name': 'Dave', 'role': 'Manager'}, {'name': 'David', 'role': 'Engineer'}]
final = {}
for dict in data:
for k,v in dict.items():
if k in final:
final[k] = ';' v
else:
final[k] = v
print(final)