I have a json object that I’m trying to group item together in.
sorted_stack = sorted(stack, key=itemgetter('Date')) for key, group in itertools.groupby(sorted_stack, key=lambda x:x['Date']): print(key) print(list(group))
this code returns values grouped by date as the key and then a list of teams and dates like this
2020-03-08 [{'Team': 'ORL', 'Date': '2020-03-08'}, {'Team': 'ORL', 'Date': '2020-03-08'}, {'Team': 'ORL', 'Date': '2020-03-08'}, {'Team': 'PHO', 'Date': '2020-03-08'}, {'Team': 'PHO', 'Date': '2020-03-08'}, {'Team': 'PHO', 'Date': '2020-03-08'}, {'Team': 'PHO', 'Date': '2020-03-08'}, {'Team': 'MIN', 'Date': '2020-03-08'}, {'Team': 'MIN', 'Date': '2020-03-08'}, {'Team': 'MIN', 'Date': '2020-03-08'}]
However, I need it to return and key value pair like this
2020-03-08 : [{'Team': 'ORL', 'Date': ['2020-03-08', '2020-03-08', '2020-03-08']}, {'Team': 'PHO', 'Date': ['2020-03-08','2020-03-08', '2020-03-08', '2020-03-08']}, {'Team': 'MIN', 'Date': ['2020-03-08','2020-03-08', '2020-03-08']}
where all the dates for a specific team are in a list as the value for the key Date
.
Advertisement
Answer
This is one approach using dict.setdefault
Ex:
for key, group in itertools.groupby(sorted_stack, key=lambda x:x['Date']): print(key) temp = {} for i in group: temp.setdefault(i['Team'], []).append(i['Date']) print(temp) #OR print([{"Team": k, "Date": v} for k, v in temp.items()])