-2

I need to sort this dictionary by points:

key: [(attacker, points), (attacker, points)]
key2: [(attacker, points), (attacker, points)]

so if I have this:

key: [(attacker, 20), (attacker, 25)]
key2: [(attacker, 5), (attacker, 10)]

I will get this:

key2: [(attacker, 5), (attacker, 10)]
key: [(attacker, 20), (attacker, 25)]
Omikor
  • 5
  • 4

2 Answers2

0

This should work, but dictionary keys will not be sorted (because it is unsorted collection) only what is inside (value) the key will be sorted because you are using the list of tuples.

for k,v in your_dict.items():
    v.sort(key=lambda i: i[1])

alikhtag
  • 316
  • 1
  • 6
0

Here goes:

from collections import OrderedDict
ordered_keys = sorted(list(my_dict.keys()), key=lambda x: x[1])
my_ordered_dict = OrderedDict((key, my_dict[key]) for key in ordered_keys)

Example input:

my_dict = {("a", 3): "toto", ("b", 2): "titi", ("c", 1): "tata"}

Output:

OrderedDict([(('c', 1), 'tata'), (('b', 2), 'titi'), (('a', 3), 'toto')])
Valentin B.
  • 602
  • 6
  • 18