Python 展平包含列表的词典的词典
我有一本字典,看起来像这样:Python 展平包含列表的词典的词典,python,dictionary,dataframe,flatten,Python,Dictionary,Dataframe,Flatten,我有一本字典,看起来像这样: data={'data': 'input', 'test': { 'and': { 'range': {'month': [{'start': 'Jan','end': 'July'}]}, 'Student': {'Name': ['ABC'], 'Class': ['10']} } } } 我需要将此dict展平到数据帧中。我尝试使用json_normalize()展平字典,得到的输出如下所示: 我期望的输
data={'data': 'input',
'test':
{
'and':
{
'range': {'month': [{'start': 'Jan','end': 'July'}]},
'Student': {'Name': ['ABC'], 'Class': ['10']}
}
}
}
我需要将此dict展平到数据帧中。我尝试使用json_normalize()展平字典,得到的输出如下所示:
我期望的输出类似于下面给出的输出
这可以在R中通过使用as.data.frame(unlist(data))来完成,但是我想在Python中做同样的展平。我是python的新手,所以我不太清楚该怎么做。我尝试通过编写递归函数来规范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
如果您需要对我的代码进行任何澄清或修改,请通知我