I tried searching for similar questions but non of the ones I found do quite what I need.
I am trying to build a generic function that can take the 2 arguments:
and convert all of the given paths to a list of flat dictionaries, suitable for outputting in CSV format.
So for example if I have a structure such as:
structure = {
"configs": [
{
"name": "config_name",
"id": 1,
"parameters": [
{
"name": "param name",
"description": "my description",
"type": "mytype",
},
{
"name": "test",
"description": "description 2",
"type": "myothertype",
"somedata": [
'data',
'data2'
]
}
]
},
{
"name": "config_name2",
"id": 2,
"parameters": [
{
"name": "param name",
"description": "my description",
"type": "mytype2",
"somedata": [
'data',
'data2'
]
},
{
"name": "test",
"description": "description 2",
"type": "myothertype2",
}
]
}
]
}
And pass the following list of paths:
paths = [
'configs.name', # notice the list structure is omitted (i.e it should be 'configs.XXX.name' where XXX is the elem id). This means I want the name entry of every dict that is in the list of configs
'configs.0.id', # similar to the above but this time I want the ID only from the first config
'configs.parameters.type' # I want the type entry of every parameter of every config
]
From this, the function should generate a list of flat dictionaries. Each entry in the list corresponds to a single row of the CSV. Each flat dictionary contains all of the selected paths.
So for example in this case I should see:
result = [
{"configs.name": "config_name", "configs.0.id": 1, "configs.parameters.type": "mytype"},
{"configs.name": "config_name", "configs.0.id": 1, "configs.parameters.type": "myothertype"},
{"configs.name": "config_name2", "configs.parameters.type": "mytype2"},
{"configs.name": "config_name2", "configs.parameters.type": "myothertype2"}
]
It needs to be able to do this for any structure passed, that contains nested dicts and lists.
You can build a lookup function that searches for values based on your rules ( get_val
). Additionally, this function takes in a match list ( match
) of valid indices which tells the function to only traverse sublists in the dictionary that have a matching index. This way, the search function can "learn" from previous searches and only return values based on the sublist positioning of previous searches:
structure = {'configs': [{'name': 'config_name', 'id': 1, 'parameters': [{'name': 'param name', 'description': 'my description', 'type': 'mytype'}, {'name': 'test', 'description': 'description 2', 'type': 'myothertype', 'somedata': ['data', 'data2']}]}, {'name': 'config_name2', 'id': 2, 'parameters': [{'name': 'param name', 'description': 'my description', 'type': 'mytype2', 'somedata': ['data', 'data2']}, {'name': 'test', 'description': 'description 2', 'type': 'myothertype2'}]}]}
def get_val(d, rule, match = None, l_matches = []):
if not rule:
yield (l_matches, d)
elif isinstance(d, list):
if rule[0].isdigit() and (match is None or match[0] == int(rule[0])):
yield from get_val(d[int(rule[0])], rule[1:], match=match if match is None else match[1:], l_matches=l_matches+[int(rule[0])])
elif match is None or not rule[0].isdigit():
for i, a in enumerate(d):
if not match or i == match[0]:
yield from get_val(a, rule, match=match if match is None else match[1:], l_matches = l_matches+[i])
else:
yield from get_val(d[rule[0]], rule[1:], match = match, l_matches = l_matches)
def evaluate(paths, struct, val = {}, rule = None):
if not paths:
yield val
else:
k = list(get_val(struct, paths[0].split('.'), match = rule))
if k:
for a, b in k:
yield from evaluate(paths[1:], struct, val={**val, paths[0]:b}, rule = a)
else:
yield from evaluate(paths[1:], struct, val=val, rule = rule)
paths = ['configs.name', 'configs.0.id', 'configs.parameters.type']
print(list(evaluate(paths, structure)))
Output:
[{'configs.name': 'config_name', 'configs.0.id': 1, 'configs.parameters.type': 'mytype'},
{'configs.name': 'config_name', 'configs.0.id': 1, 'configs.parameters.type': 'myothertype'},
{'configs.name': 'config_name2', 'configs.parameters.type': 'mytype2'},
{'configs.name': 'config_name2', 'configs.parameters.type': 'myothertype2'}]
Edit: it is best to sort your input paths by path depth in the tree:
def get_depth(d, path, c = 0):
if not path:
yield c
elif isinstance(d, dict) or path[0].isdigit():
yield from get_depth(d[path[0] if isinstance(d, dict) else int(path[0])], path[1:], c+1)
else:
yield from [i for b in d for i in get_depth(b, path, c)]
This function will find the depth in the tree at which the path's target value exists. Then, to apply to the main code:
structure = {'configs': [{'id': 1, 'name': 'declaration', 'parameters': [{'int-param': 0, 'description': 'decription1', 'name': 'name1', 'type': 'mytype1'}, {'int-param': 1, 'description': 'description2', 'list-param': ['param0'], 'name': 'name2', 'type': 'mytype2'}]}]}
paths1 = ['configs.id', 'configs.parameters.name', 'configs.parameters.int-param']
paths2 = ['configs.parameters.name', 'configs.id', 'configs.parameters.int-param']
print(list(evaluate(sorted(paths1, key=lambda x:max(get_depth(structure, x.split('.')))), structure)))
print(list(evaluate(sorted(paths2, key=lambda x:max(get_depth(structure, x.split('.')))), structure)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.