python字符串列表转换为dict列表

时间:2016-03-27 02:02:58

标签: python json list dictionary

我正在尝试像这样转换字符串列表

['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action"}']

这样的dict列表

[{"What is the purpose of a noun?":"To name something or someone."}, {"What       is the purpose of a verb?":"To show action"}]  

这就是txt文件中的原始字符串

{"What is the purpose of a noun?":"To name something or someone."}
{"What is the purpose of a verb?":"To show action in a sentence."}  

json模块不起作用

a = []
with open("proans.txt",'r') as proans:
    #transform string in the txt file into list of string by \n
    pa = proans.read().split('\n')
    #iterate through the list of string, convert string to dict and put them                           
    #into a list
    for i in range(len(pa)):
        json_acceptable_string = pa[i].replace("\"", "'")
        ret_dict = json.loads(json_acceptable_string)
        a.append(ret_dict)  

我得到了这样的错误

ValueError: Expecting property name: line 1 column 2 (char 1)  

如何将此类型的字符串列表转换为dict列表?感谢

1 个答案:

答案 0 :(得分:1)

摆脱替换线:json_acceptable_string = ...。没有必要逃避引用。

>>> lst = ['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action"}']
>>> import json
>>> [json.loads(el) for el in lst]
[{u'What is the purpose of a noun?': u'To name something or someone.'}, {u'What is the purpose of a verb?': u'To show action'}]
>>> [json.loads(el.replace("\"", "'")) for el in lst]
Traceback (most recent call last):
  ...
ValueError: Expecting property name: line 1 column 2 (char 1)

与具有StringIO对象的原始代码类似的示例:

>>> proans = StringIO.StringIO("""{"What is the purpose of a noun?":"To name something or someone."}
... {"What is the purpose of a verb?":"To show action in a sentence."}""")
>>> pa = proans.read().split('\n')
>>> proans
['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action in a sentence."}']
>>> for i in range(len(pa)):
...     print json.loads(pa[i])
...
{u'What is the purpose of a noun?': u'To name something or someone.'}
{u'What is the purpose of a verb?': u'To show action in a sentence.'}