OrderedDict for older versions of python

前端 未结 7 2140
春和景丽
春和景丽 2020-11-27 17:59

Ordered dictionaries are extremely useful structures, but unfortunately these are quite recent only working in versions from 3.1 and 2.7. How can I use an ordered dictionary

7条回答
  •  时光说笑
    2020-11-27 18:13

    For those who can't depend on the user having pip for some reason, here is a really terrible implementaiton of OrderedDict (it is immutable, has most of the features but none of the performance boost).

    class OrderedDict(tuple):
        '''A really terrible implementation of OrderedDict (for python < 2.7)'''
        def __new__(cls, constructor, *args):
            items = tuple(constructor)
            values = tuple(n[1] for n in items)
            out = tuple.__new__(cls, (n[0] for n in items))
            out.keys = lambda: out
            out.items = lambda: items
            out.values = lambda: values
            return out
    
        def __getitem__(self, key):
            try:
                return next(v for (k, v) in self.items() if k == key)
            except:
                raise KeyError(key)
    

提交回复
热议问题