ramadhuta
ramadhuta

Reputation: 55

Convert improperly formatted string into dictionary?

The problem right now is that I have a string

'{ecl:gry, hcl:#888785, eyr:2023, cid:63, iyr:2019, hgt:177cm, pid:656793259}'

I wouldn't be able to ast.literal_eval convert this to a dict because it isn't properly formatted. So I tried wrapping alphanumeric characters with quotations.

        output = ""
        quoting = False
        for char in string:
            if char.isalnum():
                if not quoting:
                    output += '"'
                    quoting = True
            elif quoting:
                output += '"'
                quoting = False 
            output += char

However, some of the key, value pairs have values with special character beginnings. Which has caused:

"hcl":#"888785",

Instead of:

"hcl":"#888785",

So the closest I've been able to get in reformatting my string for ast.literal_eval() is

{"ecl":"gry", "hcl":#"888785", "eyr":"2023", "cid":"63", "iyr":"2019", "hgt":"177cm", "pid":"656793259"}

How can I be inclusive of special characters while still converting this string into a dictionary?

Upvotes: 3

Views: 74

Answers (2)

gmdev
gmdev

Reputation: 3155

You can make use of split and strip inside of a generator expression to make this work in one line:

s = "{ecl:gry, hcl:#888785, eyr:2023, cid:63, iyr:2019, hgt:177cm, pid:656793259}"
d = dict(e.split(":") for e in s.strip("{},").split())

Upvotes: 1

Tom Myddeltyn
Tom Myddeltyn

Reputation: 1375

Here is a oneliner that will do it. This strips off the { and } characters, splits on ', ' then further splits each result on :. Those results then become key value pairs creating a dictionary.

sval= '{ecl:gry, hcl:#888785, eyr:2023, cid:63, iyr:2019, hgt:177cm, pid:656793259}'
sval = {k:v for (k,v) in [s.split(':') for s in sval.strip('{}').split(', ')]}
>>> sval
{'ecl': 'gry', 'hcl': '#888785', 'eyr': '2023', 'cid': '63', 'iyr': '2019', 'hgt': '177cm', 'pid': '656793259'}

Upvotes: 1

Related Questions