【问题标题】:How to get the values from dictionary when keys are given in a list列表中给出键时如何从字典中获取值
【发布时间】:2021-10-07 21:52:09
【问题描述】:

我对 python 有点陌生,需要帮助,

dict_o = {'chamcham': 200,
          'kajukatli': 400,
          'jalebi': 1000,
          'chowmen': 1500,
          'outsourced':{'samosa': 200,
                      'mungfali': 400,
                      'springrolls': 1000,
                     'chomen': 1800}}

我想要列表中提供的值,例如

list = ['chamcham',"['outsourced']['springrolls']"]

(以这种方式指定列表是错误的语法)。

换句话说,我们如何获取“chamcham”和“springrolls”的值,这是“外包”嵌套字典中的嵌套键。需要哪个值的键是列表

我提到了How to retrieve values from nested dictionary given list of keys?,但这仅适用于列表只有嵌套元素而不是嵌套键和第一级键的组合。

【问题讨论】:

    标签: python python-3.x list dictionary nested


    【解决方案1】:

    您可以修改将值存储到两个不同列表和字典中的方式,这样会更好,但由于您需要解决方案,所以让我们稍微更改一下您的列表:

    dict_o = {'chamcham': 200,
              'kajukatli': 400,
              'jalebi': 1000,
              'chowmen': 1500,
              'outsourced':{'samosa': 200,
                          'mungfali': 400,
                          'springrolls': 1000,
                         'chomen': 1800}}
    items = ['chamcham',['springrolls']]    # you need not store outsourced things as a string store these as another list and prevent from using python function names as vairable names
    
    # now iterate thorugh the list and get the values from the dictionary
    for item in items:
        if(type(item) == list):    # checks if item is a list or not
            for i in item:
                try:
                    print(dict_o['outsourced'][i])
                except KeyError:
                    print(f'{i} not available.')
        else:
            try:
                print(dict_o[item]
            except KeyError:
                print(f'{item} is not available.')
    

    【讨论】:

      猜你喜欢
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 2022-06-21
      • 2022-11-18
      • 2017-07-27
      • 1970-01-01
      相关资源
      最近更新 更多