将字符串转换为字典列表Python 3

时间:2017-11-10 21:33:14

标签: python string python-3.x list dictionary

我有一条信息如下:

[{"city": "Beverly Hills", "state": "", "postal_code": "", "address": "Some Address", "country": "USA"}, {"city": "New York", "state": "NY", "postal_code": "", "address": "P.O. BOX 52404", "country": "USA"}]

当我type()时,它显示为<class 'str'>

如何从字符串中获取此信息到Python 3中的词典列表?

我已尝试literal_eval并收到错误malformed node or string:,因此我不确定最佳方法是什么。'

修改

以下是一个应该可重现的例子:

mydata = {'programs': '["France"]', 'ids': '[]', 'citizenships': '[]', 'nationalities': '["FR"]', 'places_of_birth': '[]', 'dates_of_birth': '["1973-03-25"]', 'addresses': '[{"state": null, "postal_code": null, "address": null, "city": null, "country": "FR"}]'}
for key,value in mydata.items():
    if type(value) is str:
        result = literal_eval(value)
        print("value 1: ", value)
        print("value type 2:", type(value))
        print("result 3: ", result)
        print("result  4: ", type(result))
        for item in result:
            print("item in result 5:", item)
            print("type of item in result 6:", type(item))

这是错误:

  

在insert_in_db中的文件“server.py”,第137行           result = literal_eval(value)
        在literal_eval中输入文件“/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py”,第84行           return _convert(node_or_string)
        _convert中的文件“/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py”,第57行           返回列表(map(_convert,node.elts))
        _convert中的文件“/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py”,第62行           在zip(node.keys,node.values))中         文件“/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py”,第61行,           对于k,v,返回dict((_ convert(k),_ convert(v))         _convert中的文件“/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py”,第83行           引发ValueError('格式错误的节点或字符串:'+ repr(节点))       ValueError:格式错误的节点或字符串:&lt; _ast.Name对象位于0x109baae48&gt;

也许我错过了检查空值的步骤?我好像在eval line 137上得到了错误。我有了从下面提到的堆栈溢出注释中使用ast.literal_eval的想法。

这是一个数据问题而不是我处理它的方式吗?我对Python不太熟悉,所以我很可能会遗漏一些东西。

4 个答案:

答案 0 :(得分:6)

import json

data = json.loads(<your_string>)

答案 1 :(得分:2)

如果您的信息类型为字符串

,则可以使用json模块
import json

data = json.loads(<your_string>)

for element in data:
    for key, value in element.items():
        print("{}: {}".format(key, value))

答案 2 :(得分:0)

那是类型列表吗?

您应该能够将变量设置为该列表,它应该可以工作。但是,如果数据是文字字符串,则可以执行此操作:

import json
test = json.loads('[{"city": "Beverly Hills", "state": "", "postal_code": "", "address": "Some Address", "country": "USA"}, {"city": "New York", "state": "NY", "postal_code": "", "address": "P.O. BOX 52404", "country": "USA"}]')

print(type(test))
-><type 'list'>

答案 3 :(得分:0)

我知道我回答得很晚,但希望它对其他人有帮助:

您可以使用:  pip安装pyyaml     导入Yaml

x = '[{"city": "Beverly Hills", "state": "", "postal_code": "", "address": "Some Address", "country": "USA"}, {"city": "New York", "state": "NY", "postal_code": "", "address": "P.O. BOX 52404", "country": "USA"}]'

x = yaml.load(x)

现在字符串已转换为词典列表。

相关问题