如何使排序的字典类? [英] How to make a sorted dictionary class?
问题描述
class SortedDict():
def __init __(self,dic =无):
self.dic = {}
如果len(dic)> 0:self.dic = dic;
def __iter __(self):
self.dic = sorted(self.dic.keys())
self.index = 0
return self
def next(self):
如果self.index + 1< len(self.dic):
self.index + = 1
return self.dic.keys()[self.index]
你不必重新发明轮子。您可以简单地将 dict
子类化,并实现 SortedDict
,像这样
$ $ $ $ $ $ $ $ $ $ $ $)))))))))))))))))))))))))))))))))))))))))))))))))
def items(self):
return self(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 ,以帮助我解决这个答案。
你可以看到< a href =http://docs.python.org/2/library/collections.html#collections.OrderedDict =nofollow> collections.OrderedDict
, dict
和 SortedDict
。
a = OrderedDict()
a [2],a [1 ],a [3] = 2,1,3
打印列表(a.items()),a.keys(),a.values()
b = { }
b [2],b [1],b [3] = 2,1,3
打印列表(b.items()),b.keys() b.values()
c = SortedDict()
c [2],c [1],c [3] = 2,1,3
打印列表(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]
I am having a hard time writing a class, which should be able to iterate through a sorted dicitonary. My main problem is at the iter-overload. I don't how to get the dic sorted.
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
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.
You can see the difference between collections.OrderedDict
, dict
and 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()
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]
这篇关于如何使排序的字典类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!