【问题标题】:Retrieving items from a nested dictionary with a nested for loop fresults in KeyError在 KeyError 中使用嵌套 for 循环从嵌套字典中检索项目
【发布时间】:2019-09-06 04:51:05
【问题描述】:

我需要系统地访问嵌套在第 3 级字典中的列表中的字典,如下所示:

responses = {'1': {'responses': [{1st dict to be retrieved}, {2nd dict to be retrieved}, ...]},
             '2': {'responses': [{1st dict to be retrieved}, {2nd dict to be retrieved}, ...]}, ...}

我需要取消嵌套并将这些嵌套的 dict 转换为数据帧,因此最终结果应如下所示:

responses = {'1': df1,
             '2': df2, ...}

为了实现这一点,我构建了一个 for 循环,以便遍历第一级的所有键。在该循环中,我使用另一个循环将嵌套字典中的每个项目提取到一个名为 responses_df 的新空列表中:

responses_dict = {}

for key in responses.keys():
    for item in responses[key]['responses']:
        responses_dict[key].update(item)

但是,我得到:

KeyError: '1'

如果我在字典中的一个键上单独使用内部循环,它就可以工作,但这并没有真正帮助我,因为数据来自 API,并且必须在生产中每隔几分钟动态更新一次。

将结果转换为数据帧的 nex 循环如下所示:

for key in responses_dict:
     responses_df[key] = pd.DataFrame.from_dict(responses_dict[key], orient='index')

但由于第一次操作失败,我还没有尝试过。

【问题讨论】:

    标签: python python-3.x for-loop


    【解决方案1】:

    试试这个:

    from collections import defaultdict      
    
    responses_dict = defaultdict(dict) # instead of {}
    

    那么你的代码就可以工作了。

    【讨论】:

    • 这是迄今为止最简单的解决方案。我以前试过这个,但不知何故直到现在才奏效。
    【解决方案2】:

    试试这个:

    responses = {'1': {'responses': [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]},
                 '2': {'responses': [{'e': 5}, {'f': 6}]}}
    
    result = {k: pd.DataFrame(chain.from_iterable(v['responses'])) for k, v in responses.items()}
    
    for df in result.values():
        print(df, end='\n\n')
    

    输出:

       0
    0  a
    1  b
    2  c
    3  d
    
       0
    0  e
    1  f
    

    【讨论】:

      【解决方案3】:

      我更喜欢在更新字典时使用字典。

      如果您使用现有键进行更新,则该键的值将被更新。 如果您使用新的键值对进行更新,则该对将被添加到该字典中。

      >>>d1 = {1: 10, 2:20}
      >>>d1.update({1:20})
      >>>d1
      >>>{1: 20, 2:20}
      
      >>>d1.update({3:30})
      >>>d1
      >>>{1: 20, 2:20, 3:30}
      

      尝试使用以下方法修复您的线路:

      responses_dict = {}
      for key in responses.keys():
          for item in responses[key]['responses']:
              responses_dict.update({key: item})
      

      所以基本上,使用字典来更新字典,更具可读性和简单性。

      【讨论】:

      • 不幸的是,这仍然只输出最后一个键列表中的最后一项,与其他响应一样。
      • 代码完全按照您的建议,输出如下所示:{'key': {'...'}。它只是一个列表项。
      【解决方案4】:

      事实上responses_dict[key] 不存在key=1

      因此,当您简单地执行 print(responses_dict[key]) 时,您会得到相同的错误,1 不是 dict 的键,并且 update 没有按应有的方式使用。

      试试下面的语法:

      responses_dict = {}
      
      for key in responses.keys():
          print(key)
          for item in responses[key]['responses']:
              responses_dict.update(key = item)
      

      【讨论】:

      • 这只会输出最后一个键中列表的最后一项,而该键只是被称为key:{'key': {'...'},所以不知何故更新函数没有被正确调用。它确实会先打印所有键,所以问题出在第二个循环中。
      猜你喜欢
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 2021-07-25
      • 2019-03-29
      • 1970-01-01
      • 2020-10-01
      相关资源
      最近更新 更多