user3302763
user3302763

Reputation: 101

Sorting lists in dictionary

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

Upvotes: 0

Views: 127

Answers (2)

Cory Kramer
Cory Kramer

Reputation: 117856

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)]
}

Upvotes: 2

Piotr Dabkowski
Piotr Dabkowski

Reputation: 5939

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]) 

Upvotes: 0

Related Questions