从lis生成嵌套字典

2024-06-16 11:36:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python3中填充一个嵌套字典,但是我不知道如何干净地完成这个任务。我想要一个更新函数,它的工作方式如下:

#pseudo code for the update given One and Two:
One = ('W/X/Y/Z.py', 1, 8)
Two = ('A/B/C/D.py', 12, 42)

#blank initialization
Dict = dict()

#structure gets created based on the path in Two
def updateDict(One, Two):
    tuple = (1, 8, 12, 42)
    try:
        Dict["A"]["B"]["C"]["D.py"]['W/X/Y/Z.py'].append(tuple)
    except:
        Dict["A"]["B"]["C"]["D.py"]['W/X/Y/Z.py'] = [tuple]
#where:
#Dict["A"] is now a dict, 
#Dict["A"]["B"] is now a dict, 
#Dict["A"]["B"]["C"] is now a dict and 
#Dict["A"]["B"]["C"]["D.py"] is now a dict
#Dict["A"]["B"]["C"]["D.py"]["W/X/Y/Z.py"] is now a list of tuples with four values

Iteratively given
One = ('W/X/Y/Z.py', 1, 8)
Two = ('A/B/C/D.py', 12, 42)

One = ('W/X/Y/Z.py', 50, 60)
Two = ('A/B/C/D.py', 90, 100)

One = ('W/X/Y/NOTZ.py', 3, 14)
Two = ('A/B/C/D.py', 15, 22)

One = ('W/X/Y/Z.py', 14, 62)
Two = ('A/B/C/NOTD.py', 13, 56)
#Would produce the following structure:
Dict = 
{"A":   {
        "B":    {
                "C":    {
                        "D.py": {
                                "W/X/Y/Z.py" : [(1,8,12,42), (50,60,90,100)],
                                "W/X/Y/NOTZ.py" : [(3,14,15,22)]
                        },
                        "NOTD.py": {
                                "W/X/Y/Z.py" : [(14,62,13,56)]
                        }
                }
        }
}}
This can be made using the following commands:
Dict = dict()
Dict["A"] = dict()
Dict["A"]["B"] = dict()
Dict["A"]["B"]["C"] = dict()
Dict["A"]["B"]["C"]["D.py"] = dict()
Dict["A"]["B"]["C"]["D.py"]["W/X/Y/Z.py"] = [(1,8,12,42), (50,60,90,100)]
Dict["A"]["B"]["C"]["D.py"]["W/X/Y/NOTZ.py"] = [(3,14,15,22)]
Dict["A"]["B"]["C"]["NOTD.py"] = dict()
Dict["A"]["B"]["C"]["NOTD.py"]["W/X/Y/Z.py"] = [(14,62,13,56)]

所以Dict[“A”][“B”][“C”]会返回一个字典:

dict(
    "D.py": {
        "W/X/Y/Z.py" : [(1,8,12,42), (50,60,90,100)],
        "W/X/Y/NOTZ.py" : [(3,14,15,22)]
     },
    "NOTD.py": {
        "W/X/Y/Z.py" : [(14,62,13,56)]
    }
)

Dict[“A”][“B”][“C”][“D.py”]将返回一个字典:

dict(
    "W/X/Y/Z.py" : [(1,8,12,42), (50,60,90,100)],
    "W/X/Y/NOTZ.py" : [(3,14,15,22)]
)

Dict[“A”][“B”][“C”][“D.py”][“W/X/Y/Z.py”]将返回元组列表:

[(1,8,12,42), (50,60,90,100)]

所以所有的嵌套值都是字典,但所有的叶子都是元组列表

一个和两个字符串中的路径在以文件名结尾之前可以是任意长度和值(因此可以得到W/X/Y/Z.py或W/X/AA.py或Q/R/S/T/U/V.py)

任何可能有助于这一点的包裹将不胜感激


Tags: andthepy字典isstructureonenow
2条回答

这里有一个版本的updateDict()可以满足您的需要(注:Py3)。它使用一个指向任意深度字典的指针d,然后将元组附加到该指针上:

Dict = dict()

def updateDict(One, Two):
    k, *v1 = One
    path, *v2 = Two
    d = Dict
    for p in path.split('/'):
        d = d.setdefault(p, {})
    d.setdefault(k, []).append(tuple(v1+v2))

In []:
One = ('W/X/Y/Z.py', 1, 8)
Two = ('A/B/C/D.py', 12, 42)
updateDict(One, Two)
Dict

Out[]:
{'A': {'B': {'C': {'D.py': {'W/X/Y/Z.py': [(1, 8, 12, 42)]}}}}}

In []:
One = ('W/X/Y/Z.py', 50, 60)
Two = ('A/B/C/D.py', 90, 100)
updateDict(One, Two)
Dict

Out[]:
{'A': {'B': {'C': {'D.py': {'W/X/Y/Z.py': [(1, 8, 12, 42), (50, 60, 90, 100)]}}}}}

等等

很难理解你在做什么。但是让我试着描述一下你需要做什么

Dict = {}
Dict.setdefault('A', {})
Dict['A'].setdefault('B', {})
Dict['A']['B'].setdefault('C', {})
Dict['A']['B']['C'].setdefault('D.py', {})
Dict['A']['B']['C']['D.py'].setdefault('W/X/Y/Z.py', set())
Dict['A']['B']['C']['D.py']['W/X/Y/Z.py'].add(???)

还有一点你需要知道,set不能添加列表。您只能添加一个数字或元组,这是不可变的。所以最后一步你应该做的是:

Dict['A']['B']['C']['D.py']['W/X/Y/Z.py'] = Dict['A']['B']['C']['D.py']['W/X/Y/Z.py'].union([1, 8, 12, 42]).union([50, 60, 90, 100])
# {1, 8, 12, 42, 50, 60, 90, 100}
# or
Dict['A']['B']['C']['D.py']['W/X/Y/Z.py'].add((1, 8, 12, 42))
Dict['A']['B']['C']['D.py']['W/X/Y/Z.py'].add((50, 60, 90, 100))
# {(1, 8, 12, 42), (50, 60, 90, 100)}

好的,我看你已经编辑了最后一步。所以现在更容易了

Dict = {}
Dict.setdefault('A', {})
Dict['A'].setdefault('B', {})
Dict['A']['B'].setdefault('C', {})
Dict['A']['B']['C'].setdefault('D.py', {})
Dict['A']['B']['C']['D.py'].setdefault('W/X/Y/Z.py', [])
Dict['A']['B']['C']['D.py']['W/X/Y/Z.py'].append(tuple)

相关问题 更多 >