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

TJB*_*TJB 4 python dictionary nested shorthand

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

master_dictionary['sub_categories'][sub_cat_name]['attributes'][attribute_name]['special_type']['nested_children'][child_cat_name][color] = blue
Run Code Online (Sandbox Code Playgroud)

以此为例

nested_child_info[color] = blue
Run Code Online (Sandbox Code Playgroud)

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

wwi*_*wii 5

类似于@fferri。您将始终必须在列表中指定项目。使用and获取对最终字典的引用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}}}}
Run Code Online (Sandbox Code Playgroud)

我也在玩一个类,但它似乎没有很多优势 - 除了您可以自定义一个关键错误异常,以便错误消息会告诉您缺少哪个深度的哪个关键。

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:\pyProjects33\tmp.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'}}}}
>>> 
Run Code Online (Sandbox Code Playgroud)


ffe*_*rri 4

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
Run Code Online (Sandbox Code Playgroud)

nested_child_info是一个引用,因此更改其内容将会更改 的内容master_dictionary