代码之家  ›  专栏  ›  技术社区  ›  Dims

是否将有序dict设置为默认值?

  •  -1
  • Dims  · 技术社区  · 6 年前

    我想键入复杂的嵌套配置,如:

    config = {
       'train': {
           'speed': 0.001,
           'initial_values': [1, 2, 3]
       },
       'model': {
    ...
       }
    }
    

    config = OrderedDict([(
        'train', OrderedDict([(
           'speed', 0.001), (
           'initial_values', [1, 2, 3])]),(
        'model', OrderedDict([(
    ...
    

    请不要用哲学来解释为什么我的愿望不好。


    def od(*args):
       return OrderedDict([(args[i], args[i+1]) for i in range(0, len(args), 2)])
    
    config = od(
        'train', od(
            'speed', 0.001,
            'initial_values', [1, 2, 3]
         ),
         'model', od(
        ...
         )
    )
    
    3 回复  |  直到 6 年前
        1
  •  5
  •   Martijn Pieters    6 年前

    不,你不能改变Python语法,不能不改变CPython源代码和重新编译,但那样它就不再是Python了。

    你所能做的就是 升级至Python 3.6或更新版本 ,字典在哪里 retain insertion order by default OrderedDict 功能集(重新排序、反转、按顺序编辑视图),然后将这些常规词典转换为 订购信息

    from collections import OrderedDict
    from functools import singledispatch
    
    @singledispatch
    def to_ordered_dict(d):
        """Convert dictionaries to OrderedDict objects, recursively
    
        Assumes you want to use current dictionary iteration order; in Python 3.7
        and newer that's the same as insertion order (or earlier if on PyPy, or 
        when using CPython, 3.6 and newer).
    
        """
        return d
    
    @to_ordered_dict.register(dict)
    def _dict(d):
        return OrderedDict(
            (to_ordered_dict(k), to_ordered_dict(v))
            for k, v in d.items()
        )
    
    @to_ordered_dict.register(list)
    @to_ordered_dict.register(tuple)
    def _sequence(s):
        return type(s)(map(to_ordered_dict, s))
    
    # add additional type registrations for other compound or container types
    

    然后坚持使用 {...} 带符号的符号 config = to_ordered_dict(config) 最后一行。

        2
  •  2
  •   Charles Landau    6 年前

    OrderedDict

    d = OrderedDict
    
    config = d([(...)])
    

    你也可以用类似的方法 .update

        3
  •  1
  •   Roman    6 年前

    from collections import OrderedDict
    import json
    
    result = json.loads(
    '''
        {
           "train": {
               "speed": 0.001,
               "initial_values": [1, 2, 3]
           },
           "model": {
                "name": "model_name",
                "wheight" : 128000
           }
        }
    ''', 
    object_pairs_hook=lambda pairs: OrderedDict(pairs))
    

    如果你有一个专门的配置文件,那么你可以这样做

    from collections import OrderedDict
    import json
    
    with open('settings.conf', 'r') as f:
        settings_str = f.read()
        settings = json.loads(settings_str, object_pairs_hook=lambda pairs: OrderedDict(pairs))
    
    推荐文章