I have a json object that I’m trying to group item together in.
JavaScript
x
5
1
sorted_stack = sorted(stack, key=itemgetter('Date'))
2
for key, group in itertools.groupby(sorted_stack, key=lambda x:x['Date']):
3
print(key)
4
print(list(group))
5
this code returns values grouped by date as the key and then a list of teams and dates like this
JavaScript
1
3
1
2020-03-08
2
[{'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'}]
3
However, I need it to return and key value pair like this
JavaScript
1
2
1
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']}
2
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:
JavaScript
1
9
1
for key, group in itertools.groupby(sorted_stack, key=lambda x:x['Date']):
2
print(key)
3
temp = {}
4
for i in group:
5
temp.setdefault(i['Team'], []).append(i['Date'])
6
print(temp)
7
#OR
8
print([{"Team": k, "Date": v} for k, v in temp.items()])
9