Sorting a dictionary of tuples in Python

烂漫一生 提交于 2019-12-04 02:51:14

Something like this?

>>> a = {'a': (1, 2, 3), 'b': (3, 2, 1)}
>>> b = a.items()
>>> b
[('a', (1, 2, 3)), ('b', (3, 2, 1))]
>>> b.sort(key=lambda x:x[1][2])  # sorting by the third item in the tuple
>>> b
[('b', (3, 2, 1)), ('a', (1, 2, 3))]

Names are easier to work with and remember that indices, so I would go with a class:

class Word(object):     # don't need `object` in Python 3
    def __init__(self, word):
        self.word = word
        self.sigma = (some calculation)
        self.sigma_sq = (some other calculation)
    def __repr__(self):
        return "Word(%r)" % self.word
    def __str__(self):
        return self.word
    @property
    def sigma(self):
        return self._sigma
    @sigma.setter               # requires python 2.6+
    def sigma(self, value):
        if not value:
            raise ValueError("sigma must be ...")
        self._sigma = value

word_list = [Word('python'), Word('totally'), Word('rocks')]
word_list.sort(key=lambda w: w.sigma_sq)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!