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

Defaultdict with tuples, sort tuples within all keys

I have following Dict:

defaultdict(<class 'list'>, {'A': [('ID1', 'Frank', 7), ('ID2', 'Peter', 1), ('ID3', 'Geoerge', 6)], 'B': [('ID1', 'FrankGeorge', 2)], 'C': [('ID1', 'Renz', 10), ('ID10', 'Mueller', 5), ('ID7', 'Dan', 2)]})

For each Key within the dict I want the tuples sorted by the third ELement. This is the expected Result:

{‘A’: [(‘ID2’, ‘Peter’, 1), (‘ID3’, ‘Geoerge’, 6), (‘ID1’, ‘Frank’, 7)],
‘B’: [(‘ID1’, ‘FrankGeorge’, 2)],
‘C’: [ (‘ID7’, ‘Dan’, 2), (‘ID10’, ‘Mueller’, 5),(‘ID1’, ‘Renz’, 10), ]}

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

I tried to run the sorted function, but it only sorted the dict by changing the key order. This is not what I want. The order of the Keys need to be the same. A,B,C is only an example. It could be way more than this.

>Solution :

Try:

from collections import defaultdict

d = defaultdict(
    list,
    {
        "A": [("ID1", "Frank", 7), ("ID2", "Peter", 1), ("ID3", "Geoerge", 6)],
        "B": [("ID1", "FrankGeorge", 2)],
        "C": [("ID1", "Renz", 10), ("ID10", "Mueller", 5), ("ID7", "Dan", 2)],
    },
)

for v in d.values():
    v.sort(key=lambda k: k[2])

print(d)

Prints:

defaultdict(<class 'list'>, {'A': [('ID2', 'Peter', 1), ('ID3', 'Geoerge', 6), ('ID1', 'Frank', 7)], 'B': [('ID1', 'FrankGeorge', 2)], 'C': [('ID7', 'Dan', 2), ('ID10', 'Mueller', 5), ('ID1', 'Renz', 10)]})
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