如何在Python中将字符串转换为字典?
2 个回答
3
正如unutbu所说,你应该使用json模块。根据你提供的示例数据,我可以这样做:
import json
import codecs
tweet = codecs.open('example.txt', encoding='utf8').read()
data = json.loads(tweet)
print keys(data)
得到的结果是:
[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']
没有错误信息。也许你可以提供一些错误情况下的示例数据,以及相关的代码?
9
你可能在寻找 json 这个模块。
比如说,
In [165]: json.loads('{"a": 0, "c": 0, "b": 0}')
Out[165]: {u'a': 0, u'b': 0, u'c': 0}