How can I sort this list of dict based on the increasing order of key?
Example input : [{'75: '0'}, {'17': '0'}, {'70': '0'}]
Desired output :
[{'17: '0'}, {'70': '0'}, {'75': '0'}]
CodePudding user response:
This can be achieved by using sort()
and a lambda function in order to give it the dict keys as the key to sort by:
to_sort = [{"75": "0"}, {"17": "0"}, {"70": "0"}]
to_sort.sort(key=lambda x: list(x.keys())[0])
This way, print(to_sort)
would give you the desired output
CodePudding user response:
You have a little typo in declaring your variable ( ' missing after '75 )
list_to_be_sorted = [{'75': '0'}, {'17': '0'}, {'70': '0'}]
We first extract keys and sort them ( I used comprehension list to make it faster you may want to use a simple for loop if that's easier )
keys_list = [int(list(key.keys())[0]) for key in list_to_be_sorted]
keys_list.sort()
then we simply fill the new list following the order of the keys on our sorted list.
output_list = []
for key in keys_list:
for dic in list_to_be_sorted:
if int(list(dic.keys())[0]) == key:
output_list.append(dic)
break
print(output_list)
CodePudding user response:
First, you need to get an array of the keys and sort them. Then loop through the sorted keys, and for each key, loop through the dictionary list, checking if it's the correct key. If it is, append it to the sorted list.
dict_list = [{17:0}, {75:0}, {70: 0}]
sorted_dict_list = []
sorted_keys = []
for dict in dict_list:
sorted_keys.extend(list(dict.keys()))
sorted_keys.sort()
for key in sorted_keys:
for dict in dict_list:
if list(dict.keys())[0] == key:
sorted_dict_list.append(dict)
break
print(sorted_dict_list) # [{17: 0}, {70: 0}, {75: 0}]
There is defiantly a more elegant way, but this is how I would do it.