Override the {…} notation so i get an OrderedDict() instead of a dict()?

后端 未结 7 655
野的像风
野的像风 2020-11-28 21:38

Update: dicts retaining insertion order is guaranteed for Python 3.7+

I want to use a .py file like a config file. So using the {.

7条回答
  •  感情败类
    2020-11-28 21:47

    If what you are looking for is a way to get easy-to-use initialization syntax - consider creating a subclass of OrderedDict and adding operators to it that update the dict, for example:

    from collections import OrderedDict
    
    class OrderedMap(OrderedDict):
        def __add__(self,other):
            self.update(other)
            return self
    
    d = OrderedMap()+{1:2}+{4:3}+{"key":"value"}
    

    d will be- OrderedMap([(1, 2), (4, 3), ('key','value')])


    Another possible syntactic-sugar example using the slicing syntax:

    class OrderedMap(OrderedDict):
        def __getitem__(self, index):
            if isinstance(index, slice):
                self[index.start] = index.stop 
                return self
            else:
                return OrderedDict.__getitem__(self, index)
    
    d = OrderedMap()[1:2][6:4][4:7]["a":"H"]
    

提交回复
热议问题