I have a function that contains code similar to the one below, which takes an OrdredDict object and a string as arguments:
def AddToOrderedDict(ordered_dict, new_key):
ordered_dict[new_key] = []
ordered_dict = OrderedDict(sorted(ordered_dict.items()))
This function will add the key to the dictionary and sort it, but not keep it sorted once it has left the function.
The code below demonstrates this behavior:
from collections import OrderedDict
def AddToOrderedDict(ordered_dict, new_key):
ordered_dict[new_key] = ['New', 'List']
ordered_dict = OrderedDict(sorted(ordered_dict.items()))
print(dict(ordered_dict))
ordered_dict = OrderedDict()
ordered_dict['A'] = ['List', 'A']
ordered_dict['C'] = ['List', 'C']
ordered_dict['D'] = ['List', 'D']
AddToOrderedDict(ordered_dict, 'B')
print(dict(ordered_dict))
Output:
{'A': ['List', 'A'], 'B': ['New', 'List'], 'C': ['List', 'C'], 'D': ['List', 'D']}
{'A': ['List', 'A'], 'C': ['List', 'C'], 'D': ['List', 'D'], 'B': ['New', 'List']}
Why is the sorting not kept outside the function?