Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 quoted?

Thanks you

like image 796
TheOneTeam Avatar asked Sep 04 '11 15:09

TheOneTeam


People also ask

How do you make a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

How do you iterate over a dictionary key?

In order to iterate only over keys you need to call keys() method that returns a new view of the dictionary's keys.

Can you loop through a dictionary Python?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.


1 Answers

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.

like image 59
phihag Avatar answered Sep 28 '22 01:09

phihag