从列表生成嵌套字典

时间:2019-03-20 02:12:33

标签: python python-3.x dictionary

我想在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)。

任何可能有助于此目的的软件包都会受到赞赏。

2 个答案:

答案 0 :(得分: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)]}}}}}

等等...

答案 1 :(得分:1)

很难理解你在做什么。但是,让我尝试描述您需要做什么。

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(???)

您需要知道的另一点是,设置无法添加列表。您只能添加数字或元组-这是不可变的。因此,您应该在下面执行最后一步:

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)