如何解析字典字符串? [英] How can I parse a dictionary string?
本文介绍了如何解析字典字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 dict
函数将字符串转换为字典,像这样
I am trying to convert a string to a dictionary with dict
function, like this
import json
p = "{'id':'12589456'}"
d = dict(p)
print d['id']
但是出现以下错误
ValueError: dictionary update sequence element #0 has length 1; 2 is required
为什么会失败?我该如何解决?
Why does it fail? How can I fix this?
推荐答案
您拥有的是字符串,但 dict
函数只能遍历元组(键值对)以构建字典。请参阅 dict
的文档。
What you have is a string, but dict
function can only iterate over tuples (key-value pairs) to construct a dictionary. See the examples given in the dict
's documentation.
在这种情况下,您可以使用 ast.literal_eval
将字符串转换为相应的 dict
对象,例如
In this particular case, you can use ast.literal_eval
to convert the string to the corresponding dict
object, like this
>>> p = "{'id':'12589456'}"
>>> from ast import literal_eval
>>> d = literal_eval(p)
>>> d['id']
'12589456'
这篇关于如何解析字典字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文