Reputation: 41
I'm pretty new to python and now for 2 days, I'm struggling with getting a hierarchical based string structure into a python dict/list structure to handle it better:
Example Strings:
Operating_System/Linux/Apache
Operating_System/Linux/Nginx
Operating_System/Windows/Docker
Operating_System/FreeBSD/Nginx
What I try to achieve is to split each string up and pack it into a python dict, that should be something like:
{'Operating_System': [{'Linux': ['Apache', 'Nginx']}, {'Windows': ['Docker']}, {'FreeBSD': ['Nginx']}]}
I tried multiple ways, including zip() and some ways by string split('/') and then doing it by nested iteration but I could not yet solve it. Does anyone know a good/elegant way to achieve something like this with python3 ?
best regards,
Chris
Upvotes: 3
Views: 291
Reputation: 28709
one way about it ... defaultdict could help here :
#assumption is that it is a collection of strings
strings = ["Operating_System/Linux/Apache",
"Operating_System/Linux/Nginx",
"Operating_System/Windows/Docker",
"Operating_System/FreeBSD/Nginx"]
from collections import defaultdict
d = defaultdict(dict)
e = defaultdict(list)
m = [entry.split('/') for entry in strings]
print(m)
[['Operating_System', 'Linux', 'Apache'],
['Operating_System', 'Linux', 'Nginx'],
['Operating_System', 'Windows', 'Docker'],
['Operating_System', 'FreeBSD', 'Nginx']]
for a,b,c in m:
e[b].append(c)
d[a] = e
print(d)
defaultdict(dict,
{'Operating_System': defaultdict(list,
{'Linux': ['Apache', 'Nginx'],
'Windows': ['Docker'],
'FreeBSD': ['Nginx']})})
if u want them exactly as u shared in ur output, u could skip the defaultdict(dict)
part :
mapp = {'Operating_System':[{k:v} for k,v in e.items()]}
mapp
{'Operating_System': [{'Linux': ['Apache', 'Nginx']},
{'Windows': ['Docker']},
{'FreeBSD': ['Nginx']}]
}
this post was also useful
Upvotes: 3