I’m attempting to sort a dictionary in Python in ascending key order. I’m trying to do this inside of a function, with the dictionary being supplied as an argument.
I understand that there are mutable and immutable datatypes in Python, and I understand that a dictionary is supposed to be a mutable datatype. That is, I should be able to pass it by-reference when supplying it as a function argument.
Usually, I would use the dict(sorted(d.items())) method, however that does not appear to work when supplying a dictionary by reference.
Here’s an example:
def CreateDict(d):
d[0] = "a"
d[4] = "b"
d[2] = "c"
d[1] = "d"
def SortDict(d):
d = dict(sorted(d.items()))
def main():
d = {}
print(d)
CreateDict(d)
print(d)
SortDict(d)
print(d)
if (__name__ == '__main__'):
main()
Where I add some elements into the dictionary d in the CreateDict function, and I try to sort it in the SortDict function. However, the output I get is the following:
{}
{0: 'a', 4: 'b', 2: 'c', 1: 'd'}
{0: 'a', 4: 'b', 2: 'c', 1: 'd'}
With d remaining unsorted even after a call to SortDict.
What is the proper way of sorting a Python dictionary when supplied by-reference as a function argument?
Thanks for reading my post, any guidance is appreciated.
>Solution :
What is the proper way of sorting a Python dictionary when supplied by-reference as a function argument?
I’d say it’s to return the new dict, and have the caller use the return value.
But, if you insist on modifying the existing dict, here are a few ways:
def SortDict(d):
items = sorted(d.items())
d.clear()
d |= items
def SortDict(d):
for k in sorted(d):
d[k] = d.pop(k)
def SortDict(d):
k = sorted(d)
d |= zip(k, map(d.pop, k))