Joylove
Joylove

Reputation: 414

Python sorting a list of dictionaries by the value of a key

Sorry my first post has to be a question. I did some searching and couldn't find the way to sort a list of dictionaries based on one key.

Assume I have this list of dictionaries

[0]{Number:123, Name:Bill, Age:32, Sex:Male}
[1]{Number:93, Name:Billy, Age:23, Sex:Male}
[2]{Number:113, Name:Billie, Age:32, Sex:Female}
[3]{Number:8, Name:Wills, Age:3, Sex: Male}
[4]{Number:8, Name:Wills, Age:4, Sex: Male}
[5]{Number:8, Name:Wills, Age:5, Sex: Male}
[6]{Number:8, Name:Wills, Age:6, Sex: Male}

I'd like to sort or iterate over this list on Number:value and then by Age:value so that the new list is like this

[0]{Number:8, Name:Wills, Age:3, Sex: Male}
[1]{Number:8, Name:Wills, Age:4, Sex: Male}
[2]{Number:8, Name:Wills, Age:5, Sex: Male}
[3]{Number:8, Name:Wills, Age:6, Sex: Male}
[4]{Number:93, Name:Billy, Age:23, Sex:Male}
[5]{Number:113, Name:Billie, Age:32, Sex:Female}
[6]{Number:123, Name:Bill, Age:32, Sex:Male}

So far I've only been able to sort a key inside the list, which sorted the dict entry within the list, and kept the list indexes the same. Which wasn't what I wanted.

sorted_data_list = sorted(data_list, key = lambda x: x['Number']) 

edit: made list contiguous.

Upvotes: 0

Views: 397

Answers (1)

user2341726
user2341726

Reputation: 392

Change the key to lambda x: (x['Number'], x['Age'])

This creates a tuple, and tuples are sorted by first element, then second element.

Upvotes: 2

Related Questions