0

Could someone please explain how I could sort a list in dictionary? For example:

B = {'Mary': [(850, 1000), (9, 10), (1000, 3000), (250, 550)], 'john': [(500, 1000), (800,3000), (20, 100), (5, 36)]}

Using the 'sorted' function, how do I sort it in ascending order based on the first value in the list? Likewise, how do I sort it in ascending order based on the second value in the list?

Many thanks

2
  • 1
    you mean the first value in the tuple? Commented Jul 15, 2014 at 18:53
  • this seems like something they should probably have covered in whatever class this is from ... Commented Jul 15, 2014 at 19:17

2 Answers 2

2

I would iterate through your items, then in-place sort based on the first element of each tuple.

B = {
      'Mary': [(850, 1000), (9, 10), (1000, 3000), (250, 550)],
      'john': [(500, 1000), (800,3000), (20, 100), (5, 36)],
    }

for item in B:
    B[item].sort(key = lambda i: i[0])

Output

{
  'john': [(5, 36), (20, 100), (500, 1000), (800, 3000)],
  'Mary': [(9, 10), (250, 550), (850, 1000), (1000, 3000)]
}
Sign up to request clarification or add additional context in comments.

2 Comments

I liked the brevity of the list comprehension, but this is much more Pythonic.
Note that iterating over a dictionary in Python 2.7 will automatically iterate over the keys. Thus, B.keys() could just be B. (source: stackoverflow.com/questions/3294889/…)
0

You have to use its key argument. Key is a function which takes the element of the iterable as an agrument and returns the value on which sorting is based:

for e in B:
    B[e] = sorted(B[e], key=lambda x: x[Element_ID]) 

Element ID is the index of the element on which you want to base your sort. So it will be 1 if you want to sort according to the second element and 0 if you want to sort according to the first element.

EDIT:

Also it would be faster to use list's sort method instead of sorted:

for e in B:
    B[e].sort(B[e], key=lambda x: x[Element_ID]) 

6 Comments

B[e].sort(key=lambda x: x[Element ID]) would be more efficient because it does not need to construct a new list.
The question asks, "... Based on the first value in the list." [Element ID] probably should be [0].
@iCodez He wanted to use sorted but anyway thank you I will add it.
@user3302763 - It's the choice of which element of the tuple you want to sort on, e.g. x[0] first element, x[1] second element.
@Casey Falk 'Likewise, how do I sort it in ascending order based on the second value in the list?' I think he wants a general method.
|

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.