假设我们要创建/维护一个具有以下键结构的字典
{
"a": {"bb": {"01": "some value 01",
"02": "some value 02",
} },
}
我们使用 dpath .new() 如下所示
import dpath
d=dict() ; print(d) # d={}
dpath.new(d,'a/bb/00/c', '00val') ; print(d) # d={'a': {'bb': [{'c': '00val'}]}}
# d # NOTE this will set :bb as a list, and set at bb[00] ie idx=0 of list bb
# d # what we want instead is d={'a': {'bb': {'00': {'c': '00val'} }}}
# d # what we want is NOT d={'a': {'bb': [ {'c': '00val'} ]}}
因此,当在路径中使用
00
时,dpath 将其翻译为列表 index at 0
而不是 dict key 00
问题是如何将按键设置为
00
?目前我必须通过设置前缀 s
来躲避它,即 s00
s01
s02
我追踪源头,发现它调用了一个 Creator,您可以将其提供给新函数。这是 dpath.new 函数中的注释:
creator 允许您传入一个创建者方法,即
负责在任意级别创建缺失的密钥
路径(请参阅 dpath.path.set 的帮助)
我从 dpath.segments 复制了 _default_creator ,并删除了每次看到数字时决定创建列表的行。这是快速而肮脏的版本:
import dpath
from dpath.segments import extend
from typing import Sequence, MutableSequence
def _literal_creator(current, segments, i, hints):
segment = segments[i]
length = len(segments)
if isinstance(current, Sequence):
segment = int(segment)
if isinstance(current, MutableSequence):
extend(current, segment)
# Infer the type from the hints provided.
if i < len(hints):
current[segment] = hints[i][1]()
else:
# Peek at the next segment to determine if we should be
# creating an array for it to access or dictionary.
if i + 1 < length:
segment_next = segments[i + 1]
else:
segment_next = None
current[segment] = {}
d = dict()
dpath.new(d, r'a/bb/00/c', '00val', creator=_literal_creator)
print(d)
输出
{'a': {'bb': {'00': {'c': '00val'}}}}
(这与问题顶部的示例不同,因为您的代码与它不匹配。您要求的“00”不在示例中。如果您愿意,我可以使其匹配。)