作者:QuincySwim | 来源:互联网 | 2022-11-28 15:19
是否有可能使默认的dict文字创建有序的dicts而不是无序的?
我想键入复杂的嵌套配置,如:
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(
...
)
)
Martijn Piet..
5
不,你不能改变Python语法,不能不改变CPython源代码和重新编译,但它不再是Python了.
您可以做的最好是 升级到Python 3.6或更高版本,其中默认情况下字典保留插入顺序.如果您必须具有完整的OrderedDict
功能集(重新排序,反转,带有排序的dict视图),那么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)
.
1> Martijn Piet..:
不,你不能改变Python语法,不能不改变CPython源代码和重新编译,但它不再是Python了.
您可以做的最好是 升级到Python 3.6或更高版本,其中默认情况下字典保留插入顺序.如果您必须具有完整的OrderedDict
功能集(重新排序,反转,带有排序的dict视图),那么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)
.
@ usr2564301:不,它没有!`OrderedDict`提供的功能仅仅是记住插入顺序.