0

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.

3
  • Sorry I had been del from a list but not this one. It is contiguous. Commented Jul 26, 2017 at 3:56
  • it's 9400 items long with 36 elements in each dict lol! Commented Jul 26, 2017 at 4:14
  • Your question's been answered, but for next time you can just include a small portion of the real data - what you've posted doesn't make sense as Python, so it's hard to figure out what you're trying to do. Commented Jul 26, 2017 at 4:17

1 Answer 1

2

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

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

Sign up to request clarification or add additional context in comments.

5 Comments

sorted_data_list = sorted(data_list, key = lambda[x]: (x['Number'], x['Age'])) gives a syntax error on the [x] (debugger says formal parameter name expected)
Should be lambda x, not lambda [x]
Oh yes, my mistake. Should be lambda x (without the []) instead
Thanks gentlemen. Marking as answer with sorted_data_list = sorted(data_list, key = lambda x: (x['Number'], x['Age']))
@Joylove no need to assume folks are gentlemen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.