6

I have created a python dictionary which has keys in this form :

11, 10, 00, 01, 20, 21, 31, 30

The keys are string

I would like to maintain my dictionary in these sorted order:

00, 10, 20, 30, 01, 11, 21, 31 

This is based on the second value of the key.

I tried this sorted(dict.items(), key = lambda s: s[1]) and got the keys like:

20, 30, 21, 31, 01, 11, 10, 00

Can somebody guide me?

3
  • Have you considered using an OrderedDict? Commented Sep 22, 2013 at 21:56
  • This question is most definitely a duplicate. :) I can't even count how many times I've seen it. Commented Sep 22, 2013 at 21:56
  • Hi. items returns list of tuples where first item is key and second is value. So if You would like to sort them by keys You should use sorted(dict.items(), key = lambda s: s[0]) but in this case You got keys ascending sorted If You would like to sort as in your example 11, 10, 00, 01, 20, 21, 31, 30 > I would like to maintain my dictionary in these sorted order: 00, 10, 20, 30, 01, 11, 21, 31 You should reverse your key in sorted function sorted(dict.items(), key = lambda s: ''.join(reversed(s[0]))) Commented Sep 22, 2013 at 22:42

2 Answers 2

4

You almost had it, but the key is the first item of the tuple:

sorted(dict.items(), key=lambda s: s[0])
Sign up to request clarification or add additional context in comments.

12 Comments

I'm reading that the "second value of the key" is probably: s[0][1]
@JonClements: Ah, good point. Thanks.
Also wouldn't hurt to use key=lambda (key, val): key[1] just to make it explicit
At this point isn't it about time someone suggested using an operator.itemgetter just to get out of the lambda mess? :P
@anu: dicts weren’t ordered at the time of writing. In Python 3.7, you can wrap this expression in dict() to get a dict again.
|
0

A dictionary uses something called hashing and it can't be sorted as such. What you can do is use dict.keys().sort(key = lambda s: s[1]) and iterate or go on from there.

2 Comments

This won't do what you expect. The .sort method to a list operates on the list in-place, and that list is ephemeral. The next time you get dict.keys() it won't be sorted. It won't be the same list.
yes you are right! x = dict.keys() and then x.sort(...) Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.