I have this dictionary/json file:
{
'animal': {
'cat': {
'Persian': {},
'British_Shorthair': {}
}
'dog': {
'Pug': {},
'Pitbull': {}
}
}
'vehicle': {
'car': {
'Mercedes': {},
'BMW': {}
}
}
And I want turn this into a list of paths, meaning sth like this:
[ [animal, cat, persian], [animal, cat, british_shorthait],
[animal, dog, pug], [animal, dog, pitbull], [vehicle, car, mercedes],
[vehicle, car, bmw] ]
My file is much bigger than the example, but the structure is the same. They're all 3 levels, meaning all the paths are the same length.
Any ideas how to do this in just a few lines of code? I used multiple for-loops to get a decent solution, but it's quite inconvenient
CodePudding user response:
What is the problem with using multiple for-loops? In this way, you could achieve the result in 'a few lines of code'.
my_dict = {
'animal': {
'cat': {
'Persian': {},
'British_Shorthair': {}
},
'dog': {
'Pug': {},
'Pitbull': {}
}
},
'vehicle': {
'car': {
'Mercedes': {},
'BMW': {}
}
}
}
my_list = []
for level1 in my_dict.keys():
for level2 in my_dict[level1].keys():
for level3 in my_dict[level1][level2].keys():
my_list.append([level1, level2, level3])
print(my_list)
>>>
[['animal', 'cat', 'Persian'], ['animal', 'cat', 'British_Shorthair'], ['animal', 'dog', 'Pug'], ['animal', 'dog', 'Pitbull'], ['vehicle', 'car', 'Mercedes'], ['vehicle', 'car', 'BMW']]
Or, using a list comprehension you could even do it in one line:
[[level1, level2, level3] for level1 in my_dict.keys() for level2 in my_dict[level1].keys() for level3 in my_dict[level1][level2].keys()]
CodePudding user response:
This solution works with structures with any number of levels (and it is short anyway).
def foo(_dict):
if not _dict:
return [[]]
return [[k, *p] for k,v in _dict.items() for p in foo(v)]