如何从长度为n的数组制作密钥

时间:2019-07-20 02:16:44

标签: python json list

我正在尝试用python生成一个字典,稍后将其转换为JSON对象。

我有一个要用作键的元素列表['element1','element2',...'elementn']。

具有以下列表:

list1 = ['thing1','thing2',...'thingn']
list2 = ['element1','element2',...'elementn']

我要创建以下JSON对象:

x = {
    'thing1' : {
        'thing2' : {
            ....
                'thingn': {}
        }
    },
    'element1' : {
        'element2' : {
            ....
                'elementn': {}
        }
    }
}

这样我就可以这样访问x:

x['thing1']['thing2]...['thingn']

并添加如下新数据:

x['thing1']['thing2]['newdata']

由于最终的JSON对象将是分层的,并且稍后将添加数据,因此我想遍历键列表并生成如上所述的分层。

1 个答案:

答案 0 :(得分:1)

它使用for循环获取元素并创建字典,并使用start获取嵌套字典以在下一个循环中创建下一个字典。

编辑:我将名称start更改为node,以便更好地描述此变量中的内容。它用于在此结构中更深入地移动,例如在树或图形中从一个节点移动到另一个节点。

x = {}

list1 = ['thing1','thing2','thingn']
list2 = ['element1','element2','elementn']

node = x  # starting node
for item in list1:
    node[item] = {}    # create new sub-dictionary
    node = node[item]  # move to new sub-dictionary

node = x  # starting node
for item in list2:
    node[item] = {}    # create new sub-dictionary
    node = node[item]  # move to new sub-dictionary

print(x)

print(x['thing1']['thing2']['thingn'])

x['thing1']['thing2']['newdata'] = "Hello World!"
print(x['thing1']['thing2']['newdata'])

编辑:与功能相同

def add(start_node, levels):
    node = start_node      # starting node
    for item in levels:
        node[item] = {}    # create new sub-dictionary
        node = node[item]  # move to new sub-dictionary
    #return node


x = {}

list1 = ['thing1','thing2','thingn']
list2 = ['element1','element2','elementn']

add(x, list1)
add(x, list2)

print(x)
print(x['thing1']['thing2']['thingn'])

x['thing1']['thing2']['newdata'] = "Hello World!"
print(x['thing1']['thing2']['newdata'])

使用.split('.')可以使用字符串'element1.element2.elementn'

add(x, 'element1.element2.elementn'.split('.'))

编辑:类似于获取价值

def add(node, levels):
    '''node: starting node'''
    for item in levels:
        node[item] = {}    # create new sub-dictionary
        node = node[item]  # move to new sub-dictionary
    #return node

def get(node, levels):
    '''node: starting node'''
    for item in levels:
        node = node[item]  # move to new sub-dictionary
    return node

x = {}

add(x, ['thing1','thing2','thingn'])
add(x, 'element1.element2.elementn'.split('.'))

x['thing1']['thing2']['newdata'] = "Hello World!"
print(x['thing1']['thing2']['newdata'])

print( get(x, ['thing1', 'thing2', 'newdata']) )
print( get(x, 'thing1.thing2.newdata'.split('.') ) )