List to nested dictionary in python

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

I have a list as follows

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

I want to construct a dictionary from the above list as follows

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

The number of items in the list is dynamic. The dictionary will be a nested dictionary till it reaches the last element of the list. Is there any way in python to do this?

回答1:

Simple one-liner:

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

For better understanding the above code can be expanded to:

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'}}} 


回答2:

Use recursion:

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'}}} 


回答3:

Using the reduce() function to access and set elements:

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]) 

The get_target() and set_target() functions are re-usable on already-built nested structures, they are not limited to building a dictionary from scratch. I adapted get_target() from an earlier, related post.

Demo:

>>> 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'}}} 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!