-2

this is my dictionary:

mydict = {
    'item_1': [7,19],
    'item_2': [0,3],
    'item_3': [54,191],
    'item_4': [41,43]
}

and I want to sort it by values so that times with the biggest difference of the two elements in the list are placed first.

This is what I want:

mydict = {
    'item_3': [54,191],
    'item_1': [7,19],
    'item_2': [0,3],
    'item_4': [41,43],
}

How would I go about doing this?

Edit:

I got a response with this

{k: v for k, v in sorted(mydict.items(), key=lambda item: abs(item[1][0]-item[1][1]),reverse=True)}

And I also read some documentation on it, but don't understand the logic, what exactly is happening here?

tkxgoogle
  • 407
  • 4
  • 11

4 Answers4

0

You cannot sort a dictionary, but you can sort keys by a certain property of values:

sorted_keys = sorted(mydict.keys(), 
                     key=lambda x: abs(mydict[x][0]-mydict[x][1]), 
                     reverse=True)
blueteeth
  • 3,330
  • 1
  • 13
  • 23
Błotosmętek
  • 12,717
  • 19
  • 29
0

You can try this:

{k: v for k, v in sorted(mydict.items(), key=lambda item: abs(item[1][0]-item[1][1]),reverse=True)}
Raghul Raj
  • 1,428
  • 9
  • 24
  • 2
    Note that you need 3.7 or later version of python interpreter to use this. See https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 – Boseong Choi Mar 07 '20 at 09:35
0

As mentioned a dictionary is not ordered, however you can get a sorted list of two-item tuples representing the key-value pairs of your dictionary:

sorted_dict = sorted(mydict.items(), key=lambda item: abs(item[1][0] - item[1][1]), reverse=True)
chuck
  • 1,420
  • 4
  • 19
0

since python3.6 dictionaries are insertion ordered (dictionaries remember the order of items inserted), so if you have a python version >=3.6 you can use:

dict(sorted(mydict.items(), key=lambda t: abs(t[1][0] - t[1][1]), reverse=True))

output:

{'item_3': [54, 191], 'item_1': [7, 19], 'item_2': [0, 3], 'item_4': [41, 43]}

for other versions of python <3.6 you can use OrderDict

kederrac
  • 16,819
  • 6
  • 32
  • 55