I want to have a dictionary from
>>> page_detail_string = urllib2.urlopen("http://graph.facebook.com/Ideas4India").read()
It returns a string like
>>> page_detail_string
'{"about":"Ideas for development of India","category":"Community","description":"Platform where you can discuss and share your ideas which you think might help in betterment of our country.\\nPlease respect other community members and do not talk politics here.","is_published":true,"talking_about_count":0,"username":"Ideas4India","were_here_count":0,"id":"250014455083430","name":"Ideas 4 India","link":"http:\\/\\/www.facebook.com\\/Ideas4India","likes":23}'
Now i want to convert it to dictionary which i can be easily done by using ast.literal_eval
>>> import ast
>>> dict_page = ast.literal_eval(page_detail_string)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python2.7/ast.py", line 63, in _convert
in zip(node.keys, node.values))
File "/usr/lib/python2.7/ast.py", line 62, in <genexpr>
return dict((_convert(k), _convert(v)) for k, v
File "/usr/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
but I think it throws this error because of
"is_published":true
Is there any way i can convert it to dictionary by stripping above key and value ("is_published":true).
Thanks
Dictionary is an unordered collection in Python which store data values like a map i.e., key:value pair. In order to convert a String into a dictionary, the stored string must be in such a way that key:value pair can be generated from it.
Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.
The variable name is placed inside the dict, which will transform them into keys, and the eval() function will extract the value of the variable from the key and create the correspondent key-value dict item (2). That's it, That simple!
You can also convert a string to a dictionary by splitting the string representation into a sequence of (key, value) pairs. Then, you can add each (key, value) pair to an initially empty dictionary after some housekeeping.
What you get is a json string, you shoule use json.loads to convert to dict
import json
json.loads(page_detail_string)
Use the json
module
import json
json.loads(page_detail_string)
To read more about the json
module, check out http://docs.python.org/2/library/json.html
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