Python: how can I parse {apple: "1", orange: "2"} in the dictionary?

I got the result, he likes it.

{
    orange: '2',
    apple: '1',
    lemon: '3'
}

I know this is not a standard JSON format, but can I parse it in the Python Dictionary type? Should it be mandatory that orange, apple, lemon ?

Thanks you

+5
source share
1 answer

This is a valid YAML (superset of JSON). Use PyYAML to analyze it:

>>> s = '''
... {
...     orange: '2',
...     apple: '1',
...     lemon: '3'
... }'''
>>> import yaml
>>> yaml.load(s)
{'orange': '2', 'lemon': '3', 'apple': '1'}

Additionally, since there is a tab space inside the string s, we better remove it before parsing in yaml.

s=s.replace('\t','')

.

+14

All Articles