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'}]
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)
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.