I have a list of product categories which I want to convert to a dictionary.
['Livestock']
['Livestock', 'Poultry']
['Livestock', 'Poultry', 'Chickens']
['Livestock', 'Ruminants']
['Livestock', 'Ruminants', 'Goats']
['Livestock', 'Ruminants', 'Cows']
['Grocery']
['Grocery', 'Food Cupboard']
['Grocery', 'Food Cupboard', 'Canned & Jarred Foods']
['Grocery', 'Food Cupboard', 'Canned & Jarred Foods', 'Soup']
['Grocery', 'Food Cupboard', 'Canned & Jarred Foods', 'Vegetables']
My expected dictionary should look like:
{
Livestock:
{
Poultry: [Chickens],
Ruminants: [Goats, Cows]
},
Grocery:{
Food Cupboard: {
Canned & Jarred Foods: [Soup,Vegetables ]
}
}
}
If you don't care too much about raw speed, this is a fairly simple solution:
cats = [
['Livestock'],
['Livestock', 'Poultry'],
['Livestock', 'Poultry', 'Chickens'],
['Livestock', 'Ruminants'],
['Livestock', 'Ruminants', 'Goats'],
['Livestock', 'Ruminants', 'Cows'],
['Grocery'],
['Grocery', 'Food Cupboard'],
['Grocery', 'Food Cupboard', 'Canned & Jarred Foods'],
['Grocery', 'Food Cupboard', 'Canned & Jarred Foods', 'Soup'],
['Grocery', 'Food Cupboard', 'Canned & Jarred Foods', 'Vegetables']
]
# only keep lists that aren't the start of another
cats = [c for c in cats if not any(sc[:len(c)] == c for sc in cats if sc != c)]
result = {}
for *nodes, last, leaf in categories:
current = result
for node in nodes:
if node not in current:
current[node] = {}
current = current[node]
if last not in current:
current[last] = []
current[last].append(leaf)
print(result)
Output:
{'Livestock': {'Poultry': ['Chickens'], 'Ruminants': ['Goats', 'Cows']}, 'Grocery': {'Food Cupboard': {'Canned & Jarred Foods': ['Soup', 'Vegetables']}}}
Note that this assumes you never pass something like this:
cats = [
['apple'],
['banana']
]
And then expect something like this:
['apple', 'banana']
The solution expects that there's always at least a single level of dictionary keys.
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.