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

user3302763
  • 101
  • 4
  • 10

2 Answers2

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)]
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • I liked the brevity of the list comprehension, but this is much more Pythonic. – Casey Falk Jul 15 '14 at 19:02
  • Note that iterating over a dictionary in Python 2.7 will automatically iterate over the keys. Thus, `B.keys()` could just be `B`. (source: http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-for-loops-in-python) – Casey Falk Jul 15 '14 at 19:03
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]) 
Piotr Dabkowski
  • 5,661
  • 5
  • 38
  • 47
  • 2
    `B[e].sort(key=lambda x: x[Element ID])` would be more efficient because it does not need to construct a new list. –  Jul 15 '14 at 18:53
  • The question asks, "... Based on the first value in the list." [Element ID] probably should be [0]. – Casey Falk Jul 15 '14 at 19:00
  • @iCodez He wanted to use sorted but anyway thank you I will add it. – Piotr Dabkowski Jul 15 '14 at 19:00
  • @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. – ScottO Jul 15 '14 at 19:00
  • @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. – Piotr Dabkowski Jul 15 '14 at 19:04
  • Yup -- and now that you clarified it makes sense. Although, I would combine `Element ID` into a single variable name (perhaps just elementID) since identifiers should never have spaces in them -- even in pseudo-code. – Casey Falk Jul 15 '14 at 19:07