1

I have this piece of code

relations = dict()
relations[('a','b','c')] = 'first'
relations[('a','c','c')] = 'third'
relations[('d','b','c')] = 'second'

relations_sorted = sorted(relations.keys(), key=lambda tup: tup[1])

for key in relations_sorted:
  print( key, relations[key])

This prints the dictionary sorted on the second element of the key tuple (solution found on StackOverflow).

(('d', 'b', 'c'), 'second')
(('a', 'b', 'c'), 'first')
(('a', 'c', 'c'), 'third')

How do I extend this to sorting on the combination of second, then first, then third element in the tuple? E.g.

(('a', 'b', 'c'), 'first')
(('d', 'b', 'c'), 'second')
(('a', 'c', 'c'), 'third')
0

2 Answers 2

4

Just use key=lambda tup: (tup[1], tup[0], tup[2])

or even faster/easier/better with operator.itemgetter:

from operator import itemgetter

relations_sorted = sorted(relations.keys(), key=itemgetter(1, 0, 2))
Sign up to request clarification or add additional context in comments.

Comments

1

Change to key=lambda tup: (tup[1], tup[0], tup[2])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.