Breaking a bracket grouped in python

Appreciate the help with a one-line idiom to do the following effectively.

I have a line with groups separated by braces, as shown below:

{1:xxxx}{2:xxxx}{3:{10:xxxx}}{4:xxxx\r\n:xxxx}.... 

How to convert this to a dictionary format?

 dict={1:'xxx',2:'xxxx',3:'{10:xxxx}'},4:'xxxx\r\n:xxxx'} 
+4
source share
2 answers

Here's how I do it:

 raw = """{1:xxxx}{2:xxxx}{3:{10:xxxx}}{4:'xxxx\r\n:xxxx'}""" def parse(raw): # split into chunks by '}{' and remove the outer '{}' parts = raw[1:-1].split('}{') for part in parts: # split by the first ':' num, data = part.split(':', 1) # yield each entry found yield int(num), data # make a dict from it print dict(parse(raw)) 

It saves '{10:xxxx}' as a string, as in your example.

0
source
 r = """(?x) { (\w+) : ( (?: [^{}] | {.+?} )+ ) } """ z = "{1:xxxx}{2:xxxx}{3:{10:xxxx}}{4:'xxxx'}" print dict(re.findall(r, z)) # {'1': 'xxxx', '3': '{10:xxxx}', '2': 'xxxx', '4': "'xxxx'"} 

Feel free to convert to a single line file, if you want - just remove (?x) and all spaces from the regular expression.

The above analysis of only one level of nesting, for processing arbitrary depth, considers a more advanced regex module that supports recursive templates:

 import regex r = """(?x) { (\w+) : ( (?: [^{}] | (?R) )+ ) } """ z = "{1:abc}{2:{3:{4:foo}}}{5:bar}" print dict(regex.findall(r, z)) # {'1': 'abc', '2': '{3:{4:foo}}', '5': 'bar'} 
+4
source

Source: https://habr.com/ru/post/1478955/


All Articles