Skip to main content
 首页 » 编程设计

python之将键列表转换为嵌套字典

2025年05月04日14cloudgamer

我正在尝试弄清楚如何创建,例如,一个看起来像这样的字典:d[keys[0]][keys[1]][keys[2]]来自这样的列表:keys = ["key1", "key2", "key3"] ...

我尝试了以下方法:

  keys = ["key1", "key2", "key3"] 
  d = {} 
  d_ref= d 
  for key_num, key in enumerate(keys): 
    if key_num < len(keys)-1: 
      d[key] = {} 
      d_ref = d[key] 
    else: 
      d_ref[key] = [] 
  print(d) 

但结果是这样的:

{'key1': {}, 'key2': {'key3': []}}

我的目标是这个输出:

{'key1' : { 'key2' : { "key3": [] } }

更新

感谢 wim 的回答,让我得到了我想要的结果:

keys = ["key1", "key2", "key3"] 
d = [] 
for key in reversed(keys): 
   d = {key: d} 
 
print(d) 

请您参考如下方法:

只需一个简单的 for 循环就可以解决问题

>>> d = {} 
>>> for k in reversed(keys): 
...     d = {k: d} 
...      
>>> d 
{'key1': {'key2': {'key3': {}}}} 

(编辑: OP 在发布后更改了问题)如果您想要一个列表作为初始值,只需更改第一个分配:

>>> d = [] 
>>> for k in reversed(keys): 
...     d = {k: d} 
...      
>>> d 
{'key1': {'key2': {'key3': []}}}