【问题标题】:How to take out a list inside a dictionary value, and add newlines to it?如何取出字典值中的列表,并添加换行符?
【发布时间】:2019-01-11 19:23:05
【问题描述】:

如何取出字典值中的列表并使其成为字典的一部分?

这是我得到的输入:

[{'id': 1, 'step_and_result': [{'step': 'stepA', 'result': 'resultA'}, {'step': 'stepB', 'result': 'resultB'}, {'step': 'stepC', 'result': 'ResultC'}], 'other_key2': random_text}]

这是我想要得到的输出:

[{'id': 1, 'step': 'stepA' + '\n' + 'stepB' + '\n' + 'stepC', 'result': 'resultA' + '\n' + 'resultB' + '\n' + 'resultC', 'other_key2': random_text}]

这样当我将字典放入数据框时,步骤和结果会显示在不同的行上,但在同一个单元格内

我主要停留在如何在列表中的字典中的列表中的列表中给出步骤和结果。感谢您的帮助。

【问题讨论】:

  • 你预计random_text会发生什么?
  • 密钥名称真的从result 变为expectedstep_and_result 中途吗?
  • 抱歉,键名应该是result 而不是expected

标签: python pandas dictionary dataframe


【解决方案1】:

正如 Peter Leimbigler 所说,结果键的预期方式很奇怪。假设您保持相同的名称,这是使用列表推导的解决方案:

    # changed first 'result' key to 'expected'
    given_input = [{'id': 1, 'step_and_result': [{'step': 'stepA', 'expected': 'resultA'}, {'step': 'stepB', 'expected': 'resultB'}, {'step': 'stepC', 'expected': 'ResultC'}], 'other_key2': random_text}]

    given_input[0]['step'] = '\n'.join([d['step'] for d in given_input[0]['step_and_result']])
    given_input[0]['result'] = '\n'.join([d['expected'] for d in given_input[0]['step_and_result']])
    given_input[0].pop('step_and_result')

【讨论】:

    【解决方案2】:

    1st,我认为您应该确保所有对象在 step_and_result 中具有相同的结果键。在您的原始示例中,stepA 结果映射到“result”字段,但在 b 和 c 中,它由“expected”映射。是否可以使用“结果”键将它们全部保留?

    如果是这样,这里有一个快速完成工作的答案:

    # this will be your converted end-result
    converted = []
    
    # we're going to iterator over each object and convert step objects into strings
    for obj in original:
      # extract the step_and_result object 
      step_objs = obj['step_and_result']
    
      # we're going to store objects in list, and later we will join the list by our new-line delimeter once we're received all the results and steps
      results = []
      steps = []
      for s in step_objs:
        step, result = s['step'], s['result']
        steps.append(step)
        results.append(result)
    
      # add them to the end result my converting the lists into strings
      converted.append({
        'id': obj['id'],
        'step': '\n'.join(steps),
        'result': '\n'.join(results),
        'other_key2': obj['other_key2']
      })
    

    【讨论】:

      【解决方案3】:

      如果您在step_and_result 中的密钥都被命名为result(不是expected),并且如果您不关心other_key2 会发生什么,这里有一个使用json_normalize 的解决方案:

      raw = [{'id': 1,
              'other_key2': 'asdf',
              'step_and_result': [{'result': 'resultA', 'step': 'stepA'},
                                  {'result': 'resultB', 'step': 'stepB'},
                                  {'result': 'ResultC', 'step': 'stepC'}]}]
      
      from pandas.io.json import json_normalize
      json_normalize(raw, record_path='step_and_result').sort_index(axis=1, ascending=False)
      
          step   result
      0  stepA  resultA
      1  stepB  resultB
      2  stepC  ResultC
      

      【讨论】:

      • 对不起,我应该更清楚,我需要在同一个单元格中的步骤 [A-C],在不同的单元格中结果 [A-C],但在索引 0 上
      【解决方案4】:

      我使用了一个函数,以便密钥可以是“预期”或“结果”。

      import pandas as pd
      l=[{'id': 1,
          'step_and_result': [{'step': 'stepA', 'result': 'resultA'}, {'step': 'stepB', 'expected': 'resultB'}, {'step': 'stepC', 'expected': 'ResultC'}],
          'other_key2': 'random_text'}]
      needed_l=l[0]['step_and_result']
      def result_or_expected(d):
          if 'expected' in d.keys():
              return d['expected']
          return d['result']
      new_dict_list={x['step']:result_or_expected(x) for x in needed_l}
      df=pd.DataFrame(list(new_dict_list.items()), columns=['Step', 'Result'])
      print(df.to_string(index=False))
      

      输出

      Step   Result
      stepA  resultA
      stepB  resultB
      stepC  ResultC
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-26
        • 1970-01-01
        相关资源
        最近更新 更多