【问题标题】:Flattening a dictionary of dictionaries that contain lists展平包含列表的字典字典
【发布时间】:2019-01-11 00:16:06
【问题描述】:

我有一个字典,看起来像这样:

data={'data': 'input',
 'test': 
 {
    'and': 
    {
    'range': {'month': [{'start': 'Jan','end': 'July'}]},
   'Student': {'Name': ['ABC'], 'Class': ['10']}
     }
  }
}

我需要将此字典展平为数据框。我尝试使用 json_normalize() 展平字典,我得到的输出如下所示:

我想要的输出类似于下面给出的输出。

这可以在 R 中使用 as.data.frame(unlist(data)) 来完成,但我想在 Python 中进行同样的展平。我是python的新手,所以我对这样做没有太多想法。

【问题讨论】:

    标签: python dictionary dataframe flatten


    【解决方案1】:

    我已尝试通过编写如下递归函数来规范化您的 json 对象:

    data={'data': 'input',
     'test': 
     {
        'and': 
        {
        'range': {'month': [{'start': 'Jan','end': 'July'}]},
       'Student': {'Name': ['ABC'], 'Class': ['10']}
         }
      }
    }
    sequence = ""
    subDicts = []
    def findAllSubDicts(data):
        global subDicts
        global sequence
        for key, value in data.items():
            sequence += key
            #print(sequence)
            if isinstance(value, str):
                subDicts.append([sequence,value])
                sequence = sequence[:sequence.rfind(".")+1]
                #print(sequence)
            elif isinstance(value, dict):
                tempSequence = sequence[:sequence.rfind(".")+1]
                sequence += "."
                #print(sequence)
                findAllSubDicts(value)
                sequence = tempSequence
            elif isinstance(value, list) and isinstance(value[0], dict):
                    sequence += "."
                    tempSequence = sequence[:sequence.rfind(".")+1]
                    #print(sequence)
                    findAllSubDicts(value[0])
                    sequence = tempSequence
            elif isinstance(value, list) and len(value)==1:
                tempSequence = sequence[:sequence.rfind(".")+1]
                subDicts.append([sequence,value[0]])
                sequence = tempSequence
        return subDicts
    
    
    
    outDict = findAllSubDicts(data)
    for i in outDict:
        print(i[0].ljust(40," "), end=" ")
        print(i[1])
    

    打印结果会给你:

    data                                     input
    test.and.range.month.start               Jan
    test.and.range.month.end                 July
    test.and.Student.Name                    ABC
    test.and.Student.Class                   10
    

    如果您需要对我的代码进行任何澄清或任何修改,请通知我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 2019-11-04
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多