列表到python中的嵌套字典

时间:2015-03-03 12:45:19

标签: python list python-2.7 dictionary

我有一个如下列表

['item1', 'item2', 'item3', 'item4']

我想从上面的列表中构建一个字典,如下所示

{
    "item1": {
        "item2": {
            "item3": "item4"
        }
    }
}

列表中的项目数是动态的。字典将是嵌套字典,直到它到达列表的最后一个元素。 在python中有没有办法做到这一点?

3 个答案:

答案 0 :(得分:9)

简单的单行:

a = ['item1', 'item2', 'item3','item4']
print reduce(lambda x, y: {y: x}, reversed(a))

为了更好地理解,上面的代码可以扩展为:

def nest_me(x, y):
    """
    Take two arguments and return a one element dict with first
    argument as a value and second as a key
    """
    return {y: x}

a = ['item1', 'item2', 'item3','item4']
rev_a = reversed(a) # ['item4', 'item3', 'item2','item1']
print reduce(
    nest_me, # Function applied until the list is reduced to one element list
    rev_a # Iterable to be reduced
)
# {'item1': {'item2': {'item3': 'item4'}}}

答案 1 :(得分:4)

使用递归:

In [10]: src = ['item1', 'item2', 'item3','item4']

In [11]: def list2dict(src_list):
    if len(src_list) > 1:
        return {src_list[0] : list2dict(src_list[1:])}
    else:
        return src_list[0]
   ....:     

In [12]: 

In [12]: list2dict(src)
Out[12]: {'item1': {'item2': {'item3': 'item4'}}}

答案 2 :(得分:3)

使用reduce() function访问和设置元素:

try:
    # Python 3 moved reduce to the functools module
    from functools import reduce
except ImportError:
    # Python 2 reduce is a built-in
    pass

def get_target(d, keys):
    return reduce(lambda d, k: d.setdefault(k, {}), keys, d)

def set_target(d, keys, value):
    parent = get_target(d, keys[:-1])
    parent[keys[-1]] = value

result = {}
set_target(result, yourlist[:-1], yourlist[-1])

get_target()set_target()函数可在已构建的嵌套结构上重用,它们不限于从头构建字典。我从earlier, related post改编了get_target()

演示:

>>> def get_target(d, keys):
...     return reduce(lambda d, k: d.setdefault(k, {}), keys, d)
... 
>>> def set_target(d, keys, value):
...     parent = get_target(d, keys[:-1])
...     parent[keys[-1]] = value
... 
>>> result = {}
>>> yourlist = ['item1', 'item2', 'item3', 'item4']
>>> set_target(result, yourlist[:-1], yourlist[-1])
>>> result
{'item1': {'item2': {'item3': 'item4'}}}
相关问题