Home > database >  Sorting tuples inside of a list in a dictionary
Sorting tuples inside of a list in a dictionary

Time:09-15

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

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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