Sorting tuples inside of a list in a dictionary

Question:

I have a dictionary where the values are lists of tuples.
Lists can be in different lengths, whereas each tuple consists of 2 numbers.
For example: dictionary

f = {diff0 : [(7, 4), (4, 8), (8, 7)], diff1 : [(3, 1), (3, 2), (3, 11)]}

Now I want to sort the numbers inside of the tuples. As a result I would like to receive:

f = {diff0 : [(4, 7), (4, 8), (7, 8)], diff1 : [(1, 3), (2, 3), (3, 11)]}

The tuples itself donĀ“t need to be sorted

I had a similar problem with sorting tuples inside of list before, but they were not part of a dictionary. In that case I solved it like this:

for s in range(len(diffA0)):
    diffA0[s] = tuple(sorted(diffA0[s]))

Here it went from diffA0 : [(7, 9), (7, 4), (7, 6), (7, 8)] to diffA0 : [(7, 9), (4, 7), (6, 7), (7, 8)]

Asked By: maxwell_742

||

Answers:

for key in f:
    for i in range(len(f[key])):
        f[key][i] = sorted(f[key][i])
Answered By: Scaro974

here is the code:

f = {"diff0" : [(7, 4), (4, 8), (8, 7)], "diff1" : [(3, 1), (3, 2), (3,11)]}

for key in f:
    for ind, tup in enumerate(f[key]):
        f[key][ind] = sorted(tup)
Answered By: CYBER HK

You can use your previous approach in a dictionary comprehension:

>>> f = {'diff0' : [(7, 4), (4, 8), (8, 7)], 'diff1' : [(3, 1), (3, 2), (3, 11)]}
>>> {k: [tuple(sorted(t)) for t in v] for k, v in f.items()}
{'diff0': [(4, 7), (4, 8), (7, 8)], 'diff1': [(1, 3), (2, 3), (3, 11)]}
Answered By: tobias_k
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.