开发者

Convert a string to a dictionary in Python?

开发者 https://www.devze.com 2023-02-04 08:52 出处:网络
I am pulling data from twitter, which is in the structure of a python dictionary, but the data is held in a string variable.

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 Pyt开发者_如何学Chon?

Thanks for the help!

EDIT: Here is an example of the data.


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}


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消