如何制作排序字典类?

Sap*_*ire 2 python dictionary

我很难写一个类,它应该能够遍历排序的字典。我的主要问题是迭代器过载。我不知道如何对 dic 进行排序。

class SortedDict():
    def __init__(self, dic = None):
        self.dic = {}
        if len(dic) > 0: self.dic = dic;

    def __iter__(self):
        self.dic = sorted(self.dic.keys())
        self.index = 0
        return self

    def next(self):
        if self.index+1 < len(self.dic):
            self.index += 1
            return self.dic.keys()[self.index]
Run Code Online (Sandbox Code Playgroud)

the*_*eye 5

您不必重新发明轮子。您可以简单地子类化dict并实现SortedDict,就像这样

class SortedDict(dict):
    def __iter__(self):
        return iter(sorted(super(SortedDict, self).__iter__()))

    def items(self):
        return iter((k, self[k]) for k in self)

    def keys(self):
        return list(self)

    def values(self):
        return [self[k] for k in self]
Run Code Online (Sandbox Code Playgroud)

感谢PokeMartijn Pieters帮助我回答这个问题。

您可以看到collections.OrderedDict,dict和之间的区别SortedDict

a = OrderedDict()
a["2"], a["1"], a["3"] = 2, 1, 3
print list(a.items()), a.keys(), a.values()

b = {}
b["2"], b["1"], b["3"] = 2, 1, 3
print list(b.items()), b.keys(), b.values()

c = SortedDict()
c["2"], c["1"], c["3"] = 2, 1, 3
print list(c.items()), c.keys(), c.values()
Run Code Online (Sandbox Code Playgroud)

输出

[('2', 2), ('1', 1), ('3', 3)] ['2', '1', '3'] [2, 1, 3]
[('1', 1), ('3', 3), ('2', 2)] ['1', '3', '2'] [1, 3, 2]
[('1', 1), ('2', 2), ('3', 3)] ['1', '2', '3'] [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)