3

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

2
  • 1
    are they individual strings or lumped into a single string? Commented May 13, 2020 at 11:12
  • Are the number of delimiters fixed at 2 or can there be greater nesting in the resulting dictionaries than there is in your example? Commented May 13, 2020 at 11:25

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Wow! Thank you very much. I didn't know defaultdict and that is very helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.