以相反顺序迭代列表并创建动态词典

时间:2018-05-23 10:50:55

标签: python list dictionary

我正在尝试创建一个从密钥列表中封装dicts的大字典: 我有以下列表:

lis = ['model', 'properties', 'config', 'properties', 'zookeeperStorageSize', 'default']

我可以按相反的顺序迭代这个列表,但是我无法创建这个大对象

这里是我想要的输出:

  {'model': {'properties': {'config': {'properties': {'zookeeperStorageSize': {'default': '50m'}}}}}} 

任何线索?

3 个答案:

答案 0 :(得分:2)

这是我的解决方案:

def listtodict(mylist, final_value):
    if len(mylist) == 1:
        return {mylist[0]:final_value}
    else:
        return {mylist[0]:listtodict(mylist[1:], final_value)}

mylist = ['model', 'properties', 'config', 'properties', 'zookeeperStorageSize', 'default']
print(listtodict(mylist, "50m"))

打印:

{'model': {'properties': {'config': {'properties': {'zookeeperStorageSize': {'default': '50m'}}}}}}

答案 1 :(得分:2)

这是一个功能解决方案,使用collections.defaultdict创建defaultdicts的嵌套defaultdict:

from collections import defaultdict
from functools import reduce
from operator import getitem

tree = lambda: defaultdict(tree)
d = tree()

def getFromDict(dataDict, mapList):
    """Iterate nested dictionary"""
    return reduce(getitem, mapList, dataDict)

lis = ['model', 'properties', 'config', 'properties', 'zookeeperStorageSize', 'default']

getFromDict(d, lis[:-1])[lis[-1]] = '50m'

print(d['model']['properties']['config']['properties']['zookeeperStorageSize']['default'])
# 50

答案 2 :(得分:0)

这应该有效:

mylist = ['model', 'properties', 'config', 'properties',    'zookeeperStorageSize', 'default']

dict1 = {}
for key in reversed(mylist):
  if mylist.index(key) == len(mylist)-1:
     dict1 = {key: '50m'}
  else:
     dict1 = {key: dict1}
print dict1

<强> O / P:

{'model': {'properties': {'config': {'properties':{'zookeeperStorageSize': {'default': '50mb'}}}}}}

其中反转函数返回反向迭代器,有关详细信息,请单击     https://docs.python.org/3/library/functions.html#reversed