在Python中处理深度嵌套词典的方便方法



我在python中有一个深嵌套的词典,这占用了很多空间。有没有办法缩写这样的东西

master_dictionary['sub_categories'][sub_cat_name]['attributes'][attribute_name]['special_type']['nested_children'][child_cat_name][color] = blue

例如

nested_child_info[color] = blue

仍然要编辑字典?我希望这是有道理的。

类似于@fferri。您将始终必须在 long 列表中指定项目。使用reducegetitem获取参考

from functools import reduce
from operator import getitem
d = {1:{2:{3:{4:5}}}}
foo = 2
items = [1,foo,3]
result = d
info = reduce(getitem, items, d)

>>> info[4]
5
>>> d
{1: {2: {3: {4: 5}}}}
>>> info[4] = 99
>>> d
{1: {2: {3: {4: 99}}}}

我也在玩一堂课,但似乎没有很多优点 - 除了您可以自定义关键错误例外,以便错误消息告诉您缺少哪个深度的密钥。

class Drilldown:
    def __init__(self, d, path):
        #self.final = reduce(getitem, path, d)
        self.final = d
        for i, item in enumerate(path, 1):
            try:
                self.final = self.final[item]
            except KeyError as e:
                msg = ''.join('[{}]' for _ in range(i))
                msg = msg.format(*path[:i])
                msg = 'The last key in the path "{}" does not exist'.format(msg)
                e.args = [msg]
                raise
    def __call__(self, item):
        return self.final[item]
    def __setitem__(self, item, value):
        self.final[item] = value
    def __getitem__(self, item):
        return self.final[item]
    def __str__(self):
        return str(self.final)
    def __repr__(self):
        return repr(self.final)
>>> z = 19
>>> items = [1,2,z]
>>> q = Drilldown(d,items)
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    q = Drilldown(d,items)
  File "C:pyProjects33tmp.py", line 32, in __init__
    self.final = self.final[item]
KeyError: 'The last key in the path "[1][2][19]" does not exist'
>>> 
>>> #normal usage
>>> items = [1,2,3]
>>> q = Drilldown(d,items)
>>> d
{1: {2: {3: {4: 5}}}}
>>> q
{4: 5}
>>> q(4)
5
>>> q[4]
5
>>> q[4] += 20
>>> q
{4: 25}
>>> d
{1: {2: {3: {4: 25}}}}
>>> q['foo'] = '99'
>>> q
{4: 25, 'foo': '99'}
>>> d
{1: {2: {3: {4: 25, 'foo': '99'}}}}
>>> 
nested_child_info = master_dictionary['sub_categories'][sub_cat_name]['attributes'][attribute_name]['special_type']['nested_children'][child_cat_name]
nested_child_info[color] = blue

nested_child_info参考,因此更改其内容将更改master_dictionary的内容。

是的,你可以。

>>> dict1 = {'foo':{'bar':{'baz':0}}}
>>> dict2 = dict1['foo']['bar']
>>> dict2['baz'] = 1
>>> dict1
{'foo': {'bar': {'baz': 1}}} # dict1 has been modified

您可以做这样的事情吗?

thing = {1: {2: {3: {4: {'hello': 'world'}}}}}
a = thing[1]
b = a[2]
c = b[3]
d = c[4]
print(d) # {'hello': 'world'}

由于字典是可变的,因此实际上将完全按照您的期望发生:

>>> test = {'outer': 'thing', 'inner': {'thing': 'im the inner thing'}}
>>> inner_thing = test['inner']
>>> inner_thing
{'thing': 'im the inner thing'}
>>> inner_thing['thing'] = 'im something new'
>>> inner_thing
{'thing': 'im something new'}
>>> test
{'outer': 'thing', 'inner': {'thing': 'im something new'}}

这是因为可变的物体是通过python中的参考来传递的,而不是作为副本传递(有关此的大量文章,所以不会详细说明(。

但是,值得注意的是,您可能实际上不想更改原始dict,因为它可能会对使用此变量的其他代码产生不希望的效果(这取决于您的代码库(。在这种情况下,我通常会进行数据副本,以避免副作用:

>>> from copy import deepcopy
>>> test = {'outer': 'thing', 'inner': {'thing': 'im the inner thing'}}
>>> new_test = deepcopy(test)
>>> inner_thing = test['inner']
>>> inner_thing['thing'] = 'im something new'
>>> test
{'outer': 'thing', 'inner': {'thing': 'im something new'}}
>>> new_test
{'outer': 'thing', 'inner': {'thing': 'im the inner thing'}}

如果您有一些"固定"键,则可以始终创建一个函数:

考虑此示例:

d = dict(a=dict(sub_categories=dict(b=1)))
def changevalue(value, lvl1, lvl2):
    d[lvl1]['sub_categories'][lvl2] = value
changevalue(2,'a','b')
print(d)
#{'a': {'sub_categories': {'b': 2}}}

在您的情况下,您想提出:

[sub_cat_name][attribute_name][child_cat_name][color] ...也许

您可以考虑使用NestedDict。这是一个比较

# dictionary
master_dictionary['sub_categories'][sub_cat_name]['attributes'][attribute_name]['special_type']['nested_children'][child_cat_name][color] = blue
# NestedDict
key = (
    'sub_categories', 
    sub_cat_name, 
    'attributes', 
    attribute_name, 
    'special_type', 
    'nested_children', 
    child_cat_name, 
    color
)
master_dictionary[key] = blue

您可以在Ndicts中找到NestedDict,在PYPI

pip install ndicts

最新更新