简体   繁体   English

将每个列表元素转换为嵌套字典键

[英]Convert each list element into a nested dictionary key

There is this list of string that I need to use to create a nested dictionary with some values ['C/A', 'C/B/A', 'C/B/B']我需要使用这个字符串列表来创建一个包含一些值的嵌套字典['C/A', 'C/B/A', 'C/B/B']

The output will be in the format {'C': {'A': [1, 2, 3], 'B': {'A': [1, 2, 3], 'B': [1, 2, 3]}}} output 的格式为{'C': {'A': [1, 2, 3], 'B': {'A': [1, 2, 3], 'B': [1, 2, 3]}}}

I've tried to use the below code to create the nested dictionary and update the value, but instead I get {'C': {'A': [1, 2, 3], 'C': {'B': {'A': [1, 2, 3], 'C': {'B': {'B': [1, 2, 3]}}}}}} as the output which is not the correct format.我尝试使用以下代码创建嵌套字典并更新值,但我得到{'C': {'A': [1, 2, 3], 'C': {'B': {'A': [1, 2, 3], 'C': {'B': {'B': [1, 2, 3]}}}}}}作为 output 格式不正确。 I'm still trying to figure out a way.我还在想办法。 any ideas?有任何想法吗?

s = ['C/A', 'C/B/A', 'C/B/B']
new = current = dict()
for each in s:
    lst = each.split('/')
    for i in range(len(lst)):
        current[lst[i]] = dict()
        if i != len(lst)-1:
            current = current[lst[i]]
        else:
            current[lst[i]] = [1,2,3]
            
print(new)

You can create a custom Tree class:您可以创建自定义Tree class:

class Tree(dict):
    '''
    Create arbitrarily nested dicts.

    >>> t = Tree()
    >>> t[1][2][3] = 4
    >>> t
    {1: {2: {3: 4}}}

    >>> t.set_nested_item('a', 'b', 'c', value=5)
    >>> t
    {1: {2: {3: 4}}, 'a': {'b': {'c': 5}}}
    '''
    
    def __missing__(self, key):
        self[key] = type(self)()
        return self[key]
    
    def set_nested_item(self, *keys, value):
        head, *rest = keys
        if not rest:
            self[head] = value
        else:
            self[head].set_nested_item(*rest, value=value)

>>> s = ['C/A', 'C/B/A', 'C/B/B']
>>> output = Tree()
>>> default = [1, 2, 3]

>>> for item in s:
...     output.set_nested_item(*item.split('/'), value=list(default))

>>> output
{'C': {'A': [1, 2, 3], 'B': {'A': [1, 2, 3], 'B': [1, 2, 3]}}}

You do not need numpy for this problem, but you may want to use recursion.你不需要 numpy 来解决这个问题,但你可能想使用递归。 Here is a recursive function add that adds a list of string keys lst and eventually a list of numbers to the dictionary d :这是一个递归 function add ,它将字符串键列表lst并最终将数字列表添加到字典d

def add(lst, d):
    key = lst[0]
    if len(lst) == 1: # if the list has only 1 element
        d[key] = [1, 2, 3] # That element is the last key
        return
    if key not in d: # Haven't seen that key before
        d[key] = dict()
    add(lst[1:], d[key]) # The recursive part

To use the function, create a new dictionary and apply the function to each splitter string:要使用 function,请创建一个新字典并将 function 应用于每个拆分器字符串:

d = dict()
for each in s:
    add(each.split("/"), d)
# d
# {'C': {'A': [1, 2, 3], 'B': {'A': [1, 2, 3], 'B': [1, 2, 3]}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM