I have a dictionary that I am converting to a list so I can sort it. The dictionary is a key/value pair. I convert it to the list, sort it, and then later convert it back to a dictionary. When I convert it back to a dictionary, it goes back to being unsorted. Can someone either help me sort it as a dictionary or how to keep my list from becoming unsorted when I convert it back to a dictionary?
# Unsorted dictionary passed in. Convert it to a list for sorting.
temp_list = [str(i) for i in unsorted_dictionary_passed_in]
temp_list.sort()
# Debug print to show list is actually sorted.
print (temp_list)
# After this function, the dictionary is no longer sorted.
final_dictionary = dict.fromkeys(temp_list, 'Value added to each key')
What am I doing wrong or need to do to keep it sorted when it becomes a dictionary?
CodePudding user response:
Maybe this helps:
dic1 = {2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2 = {}
for i in sorted(dic1):
dic2[i]=dic1[i]
print(dic2)
Result:
{1: 100, 2: 90, 3: 5, 5: 67, 8: 3}