Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning nested curly braces into a dict python

I have a file that looks like this:

{val1 {val2 {d1 d2 d3}}}

I would like to make a dict or another suitable data structure so that accessing the structure like so:

data[val1][val2]

will output the data values d1, d2, d3 in another suitable data structure such as a list, tuple, or set.

Is there a built-in library function that can do this or can anyone suggest an easy way to do this?

Note: the number of data points d1 d2 d3 may not be constant, so for a different set of values I could have d1 d2 d3 d4 d5 etc.

Edit: I should add that I wrote the output, so I can change the braces to something completely different if needs be.

like image 402
user1654183 Avatar asked Aug 06 '26 09:08

user1654183


1 Answers

If all your data is as simple as the example, you can do some string manipulation to turn it into json.

import re, json
data = '{val1 {val2 {d1 d2 d3}}}'
data = re.sub(r'(\w+)', r'"\1"', data)      # {"val1" {"val2" {"d1" "d2" "d3"}}}
data = re.sub(r'"\s*{', r'": {', data)      # {"val1": {"val2": {"d1" "d2" "d3"}}}
data = re.sub(r'" "', r'", "', data)        # {"val1": {"val2": {"d1", "d2", "d3"}}}
data = re.sub(r'{([^{}]*)}', r'[\1]', data) # {"val1": {"val2": ["d1", "d2", "d3"]}}
json.loads(data)

If you also have data with more complex nesting, you will probably have to add a step or two more to add or remove commas before it is valid json.

like image 82
Håken Lid Avatar answered Aug 08 '26 00:08

Håken Lid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!