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 ?
CodePudding user response:
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]}
CodePudding user response:
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).