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 ?
>Solution :
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]}