开发者

Python: How can I parse { apple: "1" , orange: "2" } into Dictionary?

I have received an output , it likes this.

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

I know it is not a standard JSON format, but is it still possible to parse into Python Dictionary type? Is it a must that orange , apple , lemon must be quo开发者_运维百科ted?

Thanks you


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

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

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

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

Otherwise, the above string cannot be parsed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜