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)}
6
  • 1
    what is your expected output Commented Feb 12, 2019 at 4:43
  • 1
    dict aren't ordered, so sorting them makes no sense. Maybe you want to use OrederedDict? Commented Feb 12, 2019 at 4:44
  • 1
    @Julien They are ordered starting with Python 3.7. Commented Feb 12, 2019 at 4:46
  • Prior to Py3.6 dicts do retain order so dict(sort_x) loses the order of sort_x. collections.OrderedDict will keep order. Commented Feb 12, 2019 at 4:47
  • @Wen-Ben my expected is same with sort_x : {('S', 'A'): (5, 8), ('S', 'C'): (8, 14), ('S', 'B'): (11, 17)}. Commented Feb 12, 2019 at 4:49

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.