Skip to content Skip to sidebar Skip to footer

Creating Dictionary-object From String That Looks Like Dictionaries

I have a string in that looks something similiar to the following: myString = 'major: 11, minor: 31, name: A=1,B=1,C=1,P=1, severity: 0, comment: this is down' I have tried this s

Solution 1:

FYI, This is NOT the complete solution ..

If this is the concrete structure of your input, and will be the constant pattern within your source, you can distinguish the comma-separated Tokens.

The difference between major: 11, and name: A=1,B=1,C=1,P=1, is that there is SPACE after the first token which makes the difference from the second token. So simply by adding a space into second split method, you can render your string properly.

So, the code should be something like this:

dict(elem.split(':') for elem in myString.split(', '))   

Pay attention to send split method. There is a SPACE and comma ...

Regarding to the JSON format, it needs more work I guess. I have no idea now ..

Solution 2:

Here's another suggestion.

Why don't you transform it into a dictionary notation.

E.g. in a first step, you replace everything between a ':' and (comma or end of input) that contains a '=' (and mybe no whitespace, I don't know) by wrapping it in braces and replacing '=' by ':'.

In a second step, wrap everything between a ':' and (comma or end of input) in ', removing trailing and leading whitespace.

Finally, you wrap it all in braces.

I still don't trust that syntax, though... maybe after a few thousand lines have been processed successfully...

Solution 3:

At least, this parses the given example correctly...

import re

def parse(s):

    rx = r"""(?x)
        (\w+) \s* : \s*
        (
            (?: \w+ = \w+,)*
            (?: \w+ = \w+)
            |
            (?: [^,]+)
        )
    """

    r = {}
    for key, valin re.findall(rx, s):
        if'='inval:
            val = dict(x.split('=') for x inval.split(','))
        r[key] = valreturn r


myString = "major: 11, minor: 31, name: A=1,B=1,C=1,P=1, severity: 0, comment: this is down"
print parse(myString)    
# {'comment': 'this is down', 'major': '11', 'name': {'A': '1', 'P': '1', 'C': '1', 'B': '1'}, 'minor': '31', 'severity': '0'}

Post a Comment for "Creating Dictionary-object From String That Looks Like Dictionaries"