Andrew
Andrew

Reputation: 3999

Convert a string to a dictionary in Python?

I am pulling data from twitter, which is in the structure of a python dictionary, but the data is held in a string variable.

How can I convert this string variable to a dictionary in Python?

Thanks for the help!

EDIT: Here is an example of the data.

Upvotes: 2

Views: 2382

Answers (2)

Spaceghost
Spaceghost

Reputation: 6985

As unutbu says, you should use the json module. Using your example data, I can do this:

import json
import codecs
tweet = codecs.open('example.txt', encoding='utf8').read()
data = json.loads(tweet)
print keys(data)

With this result:

[u'favorited', u'in_reply_to_user_id', u'retweeted_status', u'contributors', u'truncated', u'entities', u'text', u'created_at', u'retweeted', u'in_reply_to_status_id', u'coordinates', u'id', u'source', u'in_reply_to_status_id_str', u'in_reply_to_screen_name', u'id_str', u'place', u'retweet_count', u'geo', u'in_reply_to_user_id_str', u'user']

No error messages. Perhaps you could include some example data for the error case along with the relevant code?

Upvotes: 3

unutbu
unutbu

Reputation: 879611

You are probably looking for the json module.

For example,

In [165]: json.loads('{"a": 0, "c": 0, "b": 0}')
Out[165]: {u'a': 0, u'b': 0, u'c': 0}

Upvotes: 9

Related Questions