-1

I have Dict ={'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]} dictionary and want to sort it based on the second element of the value which is a list.

I tried OrderedDict = sorted(Dict.items(), key=lambda x: x[1][1]) but it returns an ordered list instead of a dictionary.

This is what I expect :

OrderedDict = {('Deblai', [100, 1]), ('Beton de propreté', [50, 2]), ('Blocage', [10, 4])}

How I can get a dictionary instead of list ?

Pythonicc
  • 3
  • 3
  • What you say you expect is a set, not a dict. – Kelly Bundy Feb 13 '22 at 17:35
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – Kelly Bundy Feb 13 '22 at 17:37
  • @KellyBundy I needed to sort it based on the second value of each list in the values of the dictionary, while the OP in this question has a dictionary with values without lists. I found some answers but they only work on earlier version of python. – Pythonicc Feb 13 '22 at 21:57
  • That's just a slightly different comparison criterion for the dict values. And what you were missing was turning the sorted items back into a dict, which the answers there show how to do. – Kelly Bundy Feb 13 '22 at 22:04

2 Answers2

1

You can do it using dictionary comprehension like this:

unsorted_dct ={'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]}
sorted_dct = {k: v for k, v in sorted(unsorted_dct.items(), key=lambda item: item[1][1])}
print(sorted_dct)

output:

{'Deblai': [100, 1], 'Beton de propreté': [50, 2], 'Blocage': [10, 4]}
Kaushal Sharma
  • 1,770
  • 13
  • 16
0

Since normal dictionaries preserve the ordering in which their keys were inserted, you're most of the way there; just take the list of items and pass it to the dict constructor. Making it an actual OrderedDict (yes, that's an actual thing) isn't necessary.

>>> my_dict = {'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]}
>>> sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1][1]))
>>> sorted_dict
{'Deblai': [100, 1], 'Beton de propreté': [50, 2], 'Blocage': [10, 4]}

You probably don't want to name your instances Dict and OrderedDict, since these are the names of standard classes (and you should name instances with snake_case instead of CamelCase regardless).

Samwise
  • 68,105
  • 3
  • 30
  • 44