How to make a sorted dictionary class?

前端 未结 2 1891
渐次进展
渐次进展 2020-12-12 01:41

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 so

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 02:13

    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. Job done, no need for a next() function.

提交回复
热议问题