Home > Back-end >  Defaultdict with tuples, sort tuples within all keys
Defaultdict with tuples, sort tuples within all keys

Time:03-23

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), ]}

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.

CodePudding user response:

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)]})

CodePudding user response:

For Python 3.7 dictionaries preserve order.

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)]
    }
)
sortedD = defaultdict(list, {k: sorted(v, key=lambda item: item[2]) for k, v in d.items()})
print(sortedD)

Expected output

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)]})
  • Related