我正在尝试将用户输入作为字典并使用以下代码在屏幕上显示
import ast
a = input("Please enter a dictionary: ")
d = ast.literal_eval(a)
print d
but this error is occuring
File "x.py", line 3, in <module>
d = ast.literal_eval(a)
File "/usr/lib64/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/usr/lib64/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
答案 0 :(得分:3)
只需转换为raw_input
,就像这样:
import ast
a = raw_input("Please enter a dictionary: ")
d = ast.literal_eval(a)
print d
<强>输出:强>
{'a': 1, 'b': 2}
<强>解释强>
input()
就像执行eval(raw_input(....))
一样,在你的情况下将字符串转换为dict,ast.literal_eval()
期待字符串不是字典。
另请注意,在python 3.x中没有raw_input()
,因为它已转换为input()
您也可以参考此post
答案 1 :(得分:2)
ast.literal_eval用于将字符串转换为dict对象,从我猜你插入{'a':1,'b':1}(dict类型),然后尝试使用ast.literal_eval。当您将dict传递给接受字符串的函数时,它会给出错误。如果你想把字典作为字符串,那么使用“{'a':1,'b':1}”
代码
>>> import ast
>>> a = input("Please enter a dictionary: ")
Please enter a dictionary: {'a':1,'b':2}
>>> d = ast.literal_eval(a)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
d = ast.literal_eval(a)
File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
>>> a = input("Please enter a dictionary: ")
Please enter a dictionary: "{'a':1,'b':2}"
>>> a
"{'a':1,'b':2}"
>>> d = ast.literal_eval(a)
>>> d
{'a': 1, 'b': 2}
答案 2 :(得分:0)
我编辑了您的代码检查差异。
import ast
a = input('Please enter a dictionary:')
d = ast.literal_eval(str(a))
print d