Home > Net >  I want to sort by the first element of a tuple which is in a dictionary
I want to sort by the first element of a tuple which is in a dictionary

Time:06-29

I want to know how I can sort by the bigger element (which is here the int 7):

{'a': (2, 0, 'a'), 'b': (4, 0, 'b'), 'c': (7, 0, 'c')}

In my entire code the sorting is done in a 'while'

Thank you.

CodePudding user response:

sorted(d.items(), key=lambda x: x[1], reverse=True)

CodePudding user response:

If I understood correctly that you want to sort by the first item in the value tuple:

d = {'a': (2, 0, 'a'), 'b': (4, 0, 'b'), 'c': (7, 0, 'c')}

sorted_d = dict(sorted(d.items(), key=lambda x:x[1][0], reverse=True))
# {'c': (7, 0, 'c'), 'b': (4, 0, 'b'), 'a': (2, 0, 'a')}

CodePudding user response:

Dictionaries can't be sorted, unless you're fine with it not being a dictionary anymore. Otherwise, it can be done with a single line of code.

new_data = sorted(data.items(), key=lambda x: x[1][0], reverse=True)

data.items() contains (key, value) pairs. The key argument indicates what we're sorting over, and in this case, it's the zeroth index of the value tuple (x[1]). Since you want the highest value at the top, we set the reverse argument to True.

Output:

[('c', (7, 0, 'c')), ('b', (4, 0, 'b')), ('a', (2, 0, 'a'))]
  • Related