Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort Dictionary by Reference? (Python 3.10)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading