开发者

How to sort dictionary by pseudo-compound key?

开发者 https://www.devze.com 2023-03-27 23:56 出处:网络
I have a dictionary: test = {} test[(1,2)] = 1 test[(4,3)] = 1 test[(1,4)] = 1 How to sort by \"pseudo compound key\": first element 开发者_开发知识库of tuple and after second element of tuple ?tes

I have a dictionary:

test = {}
test[(1,2)] = 1
test[(4,3)] = 1
test[(1,4)] = 1

How to sort by "pseudo compound key": first element 开发者_开发知识库of tuple and after second element of tuple ?


test = {}
test[(1,2)] = 1
test[(4,3)] = 2
test[(1,4)] = 3

print sorted(test.iteritems())

Will give you:

[((1, 2), 1), ((1, 4), 3), ((4, 3), 2)]

If you want them back as a dictionary:

import OrderedDict
sorted_test = OrderedDict(sorted(test.iteritems()))

You've got a dictionary sorted by it's keys.

This all works because by default, tuples sort as you described.


Dictionaries cannot be sorted by definition. What you can do is get the list of keys, sort it, and then refer to the dictionary in given order. For example:

test = {}
test[(1,2)] = 1
test[(4,3)] = 2
test[(1,4)] = 3

keys = sorted(test.keys()) # nothing fancy, default sort
for key in keys:
   print test[key]

>>> 1
>>> 3
>>> 2


It depends on exactly what you want. If you want the keys of test sorted in that order, all you need is

sorted(test)

If you want the values of the sorted keys, then do

[test[key] for key in sorted(test)]
0

精彩评论

暂无评论...
验证码 换一张
取 消