I want to group a list of dictionaries by a key. The following code is working.
from itertools import groupby
from operator import itemgetter
user_dict = {123: [
{'the_id': 1, 'title': 'Title1'},
{'the_id': 1, 'title': 'Title1'},
{'the_id': 3, 'title': 'Title3'},
{'the_id': 2, 'title': 'Title2'}
]}
for user in user_dict:
for id, value in groupby(user_dict[user], key=itemgetter('the_id')):
titles = []
for k in value:
titles.append(k['title'])
print(titles)
It results:
['Title1', 'Title1']
['Title3']
['Title2']
When I change the order in the dict, the "grouping" doesn’t work anymore.
from itertools import groupby
from operator import itemgetter
user_dict = {123: [
{'the_id': 1, 'title': 'Title1'},
{'the_id': 3, 'title': 'Title3'},
{'the_id': 2, 'title': 'Title2'},
{'the_id': 1, 'title': 'Title1'}
]}
for user in user_dict:
for id, value in groupby(user_dict[user], key=itemgetter('the_id')):
titles = []
for k in value:
titles.append(k['title'])
print(titles)
This results to:
['Title1']
['Title3']
['Title2']
['Title1']
Can someone explain me that? How is the code correct?
Thanks.
>Solution :
You can sort the list of dictionaries before passing it to the groupby function to ensure grouping based on the 'the_id' key.
from itertools import groupby
from operator import itemgetter
user_dict = {123: [
{'the_id': 1, 'title': 'Title1'},
{'the_id': 3, 'title': 'Title3'},
{'the_id': 2, 'title': 'Title2'},
{'the_id': 1, 'title': 'Title1'}
]}
for user in user_dict:
sorted_list = sorted(user_dict[user], key=itemgetter('the_id'))
for id, value in groupby(sorted_list, key=itemgetter('the_id')):
titles = []
for k in value:
titles.append(k['title'])
print(titles)