gpt4 book ai didi

python - 当给定复合键 'foo.bar.baz' 时递归设置 Python dict 项

转载 作者:太空狗 更新时间:2023-10-29 20:26:59 24 4
gpt4 key购买 nike

我想实现以下目标:

foodict['foo.bar.baz'] = 'foo'
{
'foo': {
'bar': {
'baz': 'foo'
}
}
}
}

...递归地创建键。

摸索了一会儿,我想到了这个:

class Config(dict):
def __init__(self, *args, **kwargs):
self.super = super(Config, self)
self.update(*args, **kwargs)

def __setitem__(self, keys, value):
keys = keys.split('.')
keys.reverse()

config = Config()

for i, k in enumerate(keys):
if i == 0:
config = Config(**{ k: value })
else:
config = Config(**{ k: config })

self.super.update(config)

最佳答案

您可能会考虑来自 Raymond Hettinger 本人的“infinite defaultdict”秘诀:

https://twitter.com/raymondh/status/343823801278140417

>>> from collections import defaultdict
>>> infinite_defaultdict = lambda: defaultdict(infinite_defaultdict)
>>> d = infinite_defaultdict()
>>> d['foo']['bar']['baz'] = 'foo'
>>> d
defaultdict(<function <lambda> at 0x1040388c8>, {'foo': defaultdict(<function <lambda> at 0x1040388c8>, {'bar': defaultdict(<function <lambda> at 0x1040388c8>, {'baz': 'foo'})})})

另一种选择是实现__missing__:

>>> class InfiniteDict(dict):
... def __missing__(self, val):
... d = InfiniteDict()
... self[val] = d
... return d
...
>>> d = InfiniteDict()
>>> d['foo']['bar']['baz'] = 'foo'
>>> d
{'foo': {'bar': {'baz': 'foo'}}}

如果您必须具有属性访问权限:

class InfiniteDict(dict):
def __missing__(self, val):
d = InfiniteDict()
self[val] = d
return d
def __getattr__(self, item):
return self.__getitem__(item)
def __setattr__(self, item, value):
super().__setitem__(item, value)

在行动中:

>>> d = InfiniteDict()
>>> d.foo.bar.baz = 'foo'
>>> d
{'foo': {'bar': {'baz': 'foo'}}}
>>>

不过,这有点草率,所以不能保证没有任何错误。并且几乎没有防范措施,例如,与实际属性的冲突:

>>> d.keys = 'should I be allowed?'
>>> d
{'foo': {'bar': {'baz': 'foo'}}, 'keys': 'should I be allowed?'}
>>> d.keys()
dict_keys(['foo', 'keys'])

关于python - 当给定复合键 'foo.bar.baz' 时递归设置 Python dict 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48729220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com