I have a function that is creating a dictionary but it is not giving me what I want I understand why it is giving me it but I am wanting it to slightly different I do not want it to add it like another item in the list I want it to add it as part of the object that is in the list.
{
"Individual": [
{
"FullName": null
},
{
"City": null
},
{
"AddressLine1": null
},
{
"State": null
},
{
"PostCode": null
},
{
"Gender": null
}
],
"AdditionalQuestion": null
}
I am wanting it to give me
{
"Individual": [
{
"FullName": null
"City": null
"AddressLine1": null
"State": null
"PostCode": null
"Gender": null
}
],
"AdditionalQuestion": null
}
I am wanting it to give me
{
"Individual": [
{
"FullName": null
"City": null
"AddressLine1": null
"State": null
"PostCode": null
"Gender": null
}
],
"AdditionalQuestion": null
}
Here is the code
def template(data):
def get_names(item):
name_entry = None
if "properties" in item:
properties = item['properties']
if properties:
name_entry = {item['name'] : [get_names(prop) for prop in properties if prop is not None and get_names(prop) is not None]}
else:
bad_names = ["id$","_link"]
if item['name'] not in bad_names:
name_entry = {item['name']: None}
if name_entry:
return name_entry
data_list = [get_names(item) for item in data if get_names(item) is not None and get_names(item) is not None]
data_dict = {}
for item in data_list:
data_dict.update(item)
return data_dict
the input is something like
[{"name": "Individual", "properties": [{"name": "FullName"},{"name": "City"},{"name": "AddressLine1"},{"name": "State"},{"name": "PostCode"},{"name": "Gender"}]},{"name": "SigningDate"}]
>Solution :
You’ve made this harder than it needs to be. Every level is the same, so recursion is the right way to handle it. At each stage, either there are "properties", which is a simple recursive call, or there isn’t:
def template(data):
out = {}
for item in data:
if 'properties' in item:
out[item['name']] = template(item['properties'])
else:
out[item['name']] = None
return out
z = [{"name": "Individual", "properties": [{"name": "FullName"},{"name": "City"},{"name": "AddressLine1"},{"name": "State"},{"name": "PostCode"},{"name": "Gender"}]},{"name": "SigningDate"}]
print(template(z))
Output:
{'Individual': {'FullName': None, 'City': None, 'AddressLine1': None, 'State': None, 'PostCode': None, 'Gender': None}, 'SigningDate': None}