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
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.
In order to iterate only over keys you need to call keys() method that returns a new view of the dictionary's keys.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With