Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

python - 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. 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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...