python - Transform a list of dicts to a new list of dicts with a different format -
what best approach transform existing list of dict shown below new list of dicts shown below?
given:
data = [{'count': 3}, {'day': '2013-07-14'}, {'count': 5}, {'day': '2013-04-14'}]
expected output:
newlist = [{'name': 'day', 'data': ['2013-07-14', '2013-04-14']}, {'name': 'count','data': [3, 5]}]
it looks trying group data together. use dict() newlist, honestly... i'll add in conversion list @ end.
basically iterate list of dicts, iterate dicts , add them new dict. using dict target easiest since let add appropriate list element. @ point, stop , use dict output, answer question fully...
then convert dict list of dicts in format looking for. there might cleverer ways of doing dict , list comprehensions, might easier way if learning.
data = [{'count': 3}, {'day': '2013-07-14'}, {'count': 5}, {'day': '2013-04-14'}] group=dict() d in data: item in d: try: group[item].append(d[item]) except keyerror: group[item] = [d[item]] newlist = [] item in group: newlist.append( {'name' : item, 'data' : group[item]} )
the contents of newlist:
>>> newlist [{'data': [3, 5], 'name': 'count'}, {'data': ['2013-07-14', '2013-04-14'], 'name': 'day'}]
Comments
Post a Comment