Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort a list of dictionaries…(Itemgetter)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading