1

I am using Python 2.5. I have a dictionary with a list of lists as values

{'a': [['6', 3]], 'b': [['5', 1], ['6', 5]], 'c': [['446', 2],['6', 11],['67', 86]] }

I want to sort it by the 2nd element of the first list item, so, the above would be sorted like this:

'b': [['5', 1], ['6', 5]], 
'c': [['446', 2],['6', 11],['67', 86]]
'a': [['6', 3]]

Any suggestions?

Thanks Scott

2 Answers 2

4

A dictionary itself is unordered, so you can't sort it per se. If you want to create a sorted list of the key-value pairs, you can do that:

sorted(myDict.iteritems(), key=lambda x: x[1][0][1])

iteritems returns an iterable of (key, value) pairs, so x[1][0][1] there means "take the second element of this pair (which is the value), and take the first element of that (which is the first list in the list of lists) and take the second element in that --- in order words, the second element in the first list, which is what you want.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Works great. And, I finally went to ready up on lambda functions.
iteritems doesn't return a list of (key, value) pairs; it iterates a lazy sequence of such pairs. If you actually want a list, you have to use items (or call list(myDict.iteritems()).
1

Dictionaries have no order.

However, there is a class in the standard library called collections.OrderedDict that retains the order of insertion. And you can create one like this:

>>> collections.OrderedDict(sorted(myDict.iteritems(), key=lambda x: x[1][0][1])
OrderedDict([('b', [['5', 1], ['6', 5]]), ('c', [['446', 2], ['6', 11], ['67', 86]]), ('a', [['5', 4]])])

myDict.iteritems() returns a sequence of (key, value) tuples. (You can also use items, which will return the sequence as a list instead of an iterator—but it will work in Python 3, which iteritems will not.)

sorted sorts them by the key.

The key is a function that takes the value from one of these tuples, the 2nd element of that value, and the 1st element of that 2nd element, which is what you wanted to sort by.

The OrderedDict class does not exist in Python 2.5, but it's implemented in pure Python. If you look at the docs for 2.7, there's a link to the code, which you can copy and paste into your 2.5 program. Or you can use the ActiveState recipe that was borrowed into the standard library, or look for a module at PyPI that does it for you.

Comments

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.