0

I have problem about sorting my dict. My code is:

x = {('S', 'A'): (5, 8), ('S', 'B'): (11, 17), ('S', 'C'): (8, 14)}

sort_x = sorted(x.items(), key=lambda kv: kv[1])
print sort_x
sort_x_dict = dict(sort_x)
print sort_x_dict

Output:

[(('S', 'A'): (5, 8)), (('S', 'C'): (8, 14)), (('S', 'B'): (11, 17))]
{('S', 'A'): (5, 8), ('S', 'B'): (11, 17), ('S', 'C'): (8, 14)}
Manzurul Hoque Rumi
  • 2,911
  • 4
  • 20
  • 43
  • 1
    what is your expected output – BENY Feb 12 '19 at 04:43
  • 1
    `dict` aren't ordered, so sorting them makes no sense. Maybe you want to use `OrederedDict`? – Julien Feb 12 '19 at 04:44
  • 1
    @Julien They are ordered starting with Python 3.7. – Selcuk Feb 12 '19 at 04:46
  • Prior to Py3.6 `dict`s do retain order so `dict(sort_x)` loses the order of `sort_x`. [`collections.OrderedDict`](https://docs.python.org/2.7/library/collections.html?highlight=ordereddict#collections.OrderedDict) will keep order. – AChampion Feb 12 '19 at 04:47
  • @Wen-Ben my expected is same with `sort_x` : `{('S', 'A'): (5, 8), ('S', 'C'): (8, 14), ('S', 'B'): (11, 17)}`. – lilis gumilang Feb 12 '19 at 04:49
  • I guess it answers your question: https://stackoverflow.com/questions/12031482/custom-sorting-python-dictionary/51471920#51471920 – Shivam Pandya Feb 12 '19 at 04:51

1 Answers1

5

It's apparent from your print statements that you're using Python 2.7, and yet dicts are only guaranteed to be ordered since Python 3.7. You can either upgrade to Python 3.7 for your exact code to work, or switch to collections.OrderedDict in place of dict:

from collections import OrderedDict
sort_x = sorted(x.items(), key=lambda kv: kv[1])
print(sort_x)
sort_x_dict = OrderedDict(sort_x)
print(sort_x_dict)
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • but my expected is : `{('S', 'A'): (5, 8), ('S', 'C'): (8, 14), ('S', 'B'): (11, 17)}` not `([(('S', 'A'), (5, 8)), (('S', 'C'), (8, 14)), (('S', 'B'), (11, 17))])` – lilis gumilang Feb 12 '19 at 05:00
  • `OrderedDict` subclasses `dict` so you can use it like a dict because it really a dict. It's only when you print it that its `__repr__` method would return a representation string that looks more like a list of tuples. But for all intents and purposes you can use an `OrderedDict` just like a regular dict. If you still want to use a regular dict to achieve what you want, again, you would have to upgrade to Python 3.7+. – blhsing Feb 12 '19 at 05:14