【问题标题】:How to access dictionary values by using elements in the list which have keys of dictionary? [duplicate]如何通过使用列表中具有字典键的元素来访问字典值? [复制]
【发布时间】:2018-12-20 09:41:21
【问题描述】:

例如我有一个字典如下

demo_dict = {1:{2:{3:{4:5}}}}

现在我在下面的列表中有值 5 的路径

path = [1,2,3,4]

现在通过使用该路径,我想将其设置为

demo_dict[1][2][3][4] # expected

【问题讨论】:

    标签: python python-2.7 list dictionary


    【解决方案1】:

    你可以使用简单的递归:

    demo_dict = {1:{2:{3:{4:5}}}}
    path = [1,2,3,4]
    def get_val(d, _path):
      return d[_path[0]] if not _path[1:] else get_val(d[_path[0]], _path[1:])
    
    print(get_val(demo_dict, path))
    

    输出:

    5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-04
      • 2013-05-22
      • 1970-01-01
      • 2023-04-06
      • 2012-12-31
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      相关资源
      最近更新 更多