【发布时间】:2016-01-21 01:52:56
【问题描述】:
我想写一个递归函数:
arguments: d, dictionary
result: list of dictionaries
def expand_dictionary(d):
return []
该函数递归地遍历字典并使用 _ 展平嵌套对象,此外它还将嵌套列表展开到数组中,并包含父标签。
考虑从文档创建关系模型。
这是一个输入和输出示例:
original_object = {
"id" : 1,
"name" : {
"first" : "Alice",
"last" : "Sample"
},
"cities" : [
{
"id" : 55,
"name" : "New York"
},
{
"id" : 60,
"name" : "Chicago"
}
],
"teachers" : [
{
"id" : 2
"name" : "Bob",
"classes" : [
{
"id" : 13,
"name" : "math"
},
{
"id" : 16,
"name" : "spanish"
}
]
}
]
}
expected_output = [
{
"id" : 1,
"name_first" : "Alice",
"name_last" : "Sample"
},
{
"_parent_object" : "cities",
"id" : 55,
"name" : "New York"
},
{
"_parent_object" : "cities",
"id" : 60,
"name" : "Chicago"
},
{
"parent_object" :"teachers",
"id" : 2,
"name" : "Bob"
},
{
"parent_object" :"teachers_classes",
"id" : 13,
"name" : "math"
},
{
"parent_object" :"teachers_classes",
"id" : 16,
"name" : "spanish"
}
]
目前用于展平的代码是:
def flatten_dictionary(d):
def expand(key, value):
if isinstance(value, dict):
return [ (key + '_' + k, v) for k, v in flatten_dictionary(value).items() ]
else:
#If value is null or empty array don't include it
if value is None or value == [] or value == '':
return []
return [ (key, value) ]
items = [ item for k, v in d.items() for item in expand(k, v) ]
return dict(items)
【问题讨论】:
-
您的“original_obejct”是字典吗?那么第一行的 '"id" : 1' 后面应该有 'comma' 吗?
-
正确,为语法错误道歉。
-
看起来你在破坏信息:如果你有不止一位老师,你能从期望的输出中分辨出每个老师教什么课程吗?
标签: python arrays dictionary recursion