Valachio
Valachio

Reputation: 1135

Python - Sort a list by a certain element in a tuple in a dictionary

data = [{'info': ('orange', 400000, 'apple'), 'photo': None}, {'info': ('grape', 485000, 'watermelon'), 'photo': None}]

I want to sort data by the 2nd element (400000, 485000) in the tuple in the dictionary. How do I do this?

I followed another answer and my closest attempt was data.sort(key=lambda tup: tup[1]), but that produces this error:

KeyError: 1

Upvotes: 1

Views: 61

Answers (3)

cs95
cs95

Reputation: 402513

Use the inplace list.sort method with a key that indexes info first, and then the data in the tuple:

data.sort(key=lambda x: x['info'][1])

Or, the not in-place sorted function:

data = sorted(data, key=lambda x: x['info'][1])

Between the two, list.sort is faster, because it sorts the data in-place, whereas sorted has to create and return a copy of the data in data.

A couple of other things you should think about;

  1. What if your dictionary does not have info as a key?
  2. What if the second element in the info tuple isn't even numeric?

Do you want sort to error out when it hits invalid data? Or would you rather introduce some means of handling these on a case-by-case basis? The key would need to change accordingly.

Upvotes: 4

codingatty
codingatty

Reputation: 2084

For each dict item in the list you want to sort, you want to take the item's value keyed by 'info', which is a list, and sort on the second item (addressed as [1], counting from zero.

So: data.sort(key=lambda item: item['info'][1])

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71451

You can sort via key:

data = [{'info': ('orange', 400000, 'apple'), 'photo': None}, {'info': ('grape', 485000, 'watermelon'), 'photo': None}]
new_data = sorted(data, key=lambda x:x.get('info', [0, 0])[1])

Upvotes: 0

Related Questions