简体   繁体   English

如何制作一个排序的字典类?

[英]How to make a sorted dictionary class?

I am having a hard time writing a class, which should be able to iterate through a sorted dicitonary. 我很难写一个类,它应该能够遍历排序的dicitonary。 My main problem is at the iter-overload. 我的主要问题是iter-overload。 I don't how to get the dic sorted. 我不怎么把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]

You don't have to reinvent the wheel. 你不必重新发明轮子。 You can simply subclass the dict and implement the SortedDict , like this 您可以简单地对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]

Thanks Poke and Martijn Pieters , for helping me with this answer. 感谢PokeMartijn Pieters帮我解决这个问题。

You can see the difference between collections.OrderedDict , dict and SortedDict . 你可以看到collections.OrderedDictdictSortedDict之间的区别。

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()

Output 产量

[('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]

Since you're willing to sort at the point you begin the iteration, all you need is: 由于您愿意在开始迭代时进行排序,因此您只需要:

def __iter__(self):
    return iter(sorted(self.dic))

__iter__ has to return an iterator, and the builtin function iter() gets one from the sorted list of keys. __iter__必须返回一个迭代器,内置函数iter()从键的排序列表中获取一个。 Job done, no need for a next() function. 完成工作,不需要next()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM