The Python Oracle

String to Dictionary in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Isolated

--

Chapters
00:00 Question
01:07 Accepted answer (Score 330)
01:31 Answer 2 (Score 24)
02:02 Answer 3 (Score 1)
02:17 Thank you

--

Full question
https://stackoverflow.com/questions/4917...

Question links:
[https://graph.facebook.com/me?access_tok...]: https://graph.facebook.com/me?access_tok...

Accepted answer links:
[JSON]: http://www.json.org/
[json]: http://docs.python.org/library/json.html
[simplejson]: http://pypi.python.org/pypi/simplejson/

Answer 2 links:
[ast.literal_eval]: http://docs.python.org/library/ast.html#...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #json #facebook #dictionary

#avk47



ACCEPTED ANSWER

Score 339


This data is JSON! You can deserialize it using the built-in json module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson module.

import json    # or `import simplejson as json` if on Python < 2.6

json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string)    # obj now contains a dict of the data



ANSWER 2

Score 24


Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.

>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'jdoe@gmail.com', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}



ANSWER 3

Score 1


In Python 3.x

import json
t_string = '{"Prajot" : 1, "Kuvalekar" : 3}'
res = json.loads(t_string)
print(res) # <dict>  {"Prajot" : 1, "Kuvalekar" : 3}