gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:59:28 24 4
gpt4 key购买 nike

我有这样一条信息:

[{"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))

这里是错误:

File "server.py", line 137, in insert_in_db result = literal_eval(value)
File "/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py", line 84, in literal_eval return _convert(node_or_string)
File "/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py", line 57, in _convert return list(map(_convert, node.elts))
File "/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py", line 62, in _convert in zip(node.keys, node.values))
File "/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py", line 61, in return dict((_convert(k), _convert(v)) for k, v
File "/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py", line 83, in _convert raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: <_ast.Name object at 0x109baae48>

也许我错过了检查空值的中间步骤?我似乎在 eval line 137 上遇到了错误.我想到了使用 ast.literal_eval来自下面提到的堆栈溢出评论。

与其我处理它的方式相比,它更像是一个数据问题吗?我对 Python 不是很熟悉,所以我很可能遗漏了一些东西。

最佳答案

import json

data = json.loads(<your_string>)

关于python - 将字符串转换为字典列表 Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47231444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com