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

Any python trick for flattening a dictionary and sorting it all at once?

I have this dictionary:

s = [{"label":["College Name"],"points":[{"start":939,"end":956,"text":"Kendriya Vidyalaya"}]},{"label":["College Name"],"points":[{"start":883,"end":904,"text":"Woodbine modern school"}]}]

I can sort it on start like this:

for annotation in sorted(s, key = lambda tup: tup['points'][0]['start']):
    print(annotation)

At the end of the day I need label, start and end. I know that I can access annotation in the loop and get to all the values I need, but then I’m pulling out the start point twice.

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

Is there any cool python trick to unpack values from a dictionary and sort on one of them all at once?

>Solution :

You mean like this?

for annotation in sorted(s, key = lambda tup: tup['points'][0]['start']):
    print(annotation["label"],annotation["points"][0]["start"],annotation["points"][0]["end"])

Or, only having to identify start by name once:

for annotation in sorted([(x["label"][0],x["points"][0]["start"],x["points"][0]["end"]) for x in s], key = lambda tup: tup[1]):
    print(annotation)
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