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

How to sort a dict of dicts by the length of a list inside child dicts

I’m a beginner to Python, and for the sake of learning I looked up some challenges to solve. Here I have a dictionary, containing several dictionaries, each having a list of dicts. My job here is to sort the dictionary, in descending order, based on which child of somedict has more elements in the key list.

somedict = {
    'a': {
        'key' : [{}, {}, ]
    },
    'b': {
        'key' : [{}, ]
    },
    'c': {
        'key' : [{}, {}, {} ]
    },
    'd': {
        'key' : [{}, {}, {}, ]
    },
    'e': {
        'key' : [{}, {}, {} ]
    },
    'f': {
        'key' : [{}, ]
    },
    'g': {
        'key' : [{}, {} ]
    },
    'h': {
        'key' : [{}, {}, {},]
    }

}

sorted_dict = sorted(somedict, key= lambda k: len(k['a']['key']))

print(sorted_dict)

While trying to use sorted(), I get:

TypeError: string indices must be integers

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

>Solution :

What you need to do is to sort the keys as a list, and from that sorted list rebuild the dict:

somedict = {
    ...
    # contents elided
}
keys = list(somedict.keys())
sorted_keys = sorted(keys, key= lambda k: len(somedict[k]['key']), reverse=True)

print(sorted_keys)

sorted_dict = {k:somedict[k] for k in sorted_keys}

print(sorted_dict)

Output

['c', 'd', 'e', 'h', 'a', 'g', 'b', 'f']
{'c': {'key': [{}, {}, {}]}, 'd': {'key': [{}, {}, {}]}, 'e': {'key': [{}, {}, {}]}, 'h': {'key': [{}, {}, {}]}, 'a': {'key': [{}, {}]}, 'g': {'key': [{}, {}]}, 'b': {'key': [{}]}, 'f': {'key': [{}]}}

And this can be shortened to one line:

sorted_dict = {k:somedict[k] for k in sorted(somedict, key=lambda k: len(somedict[k]['key']), reverse=True)}
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