我很难写一个类,它应该能够遍历排序的dicitonary。我的主要问题是iter-overload。我不知道怎么把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]
答案 0 :(得分:4)
您不必重新发明轮子。您可以简单地继承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]
感谢Poke和Martijn 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()
<强>输出强>
[('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]
答案 1 :(得分:3)
由于您愿意在开始迭代时进行排序,所以您只需要:
def __iter__(self):
return iter(sorted(self.dic))
__iter__
必须返回一个迭代器,内置函数iter()
从排序的键列表中获取一个。完成工作,无需next()
功能。