3

i am trying to take user input as dictionary and displaying it on the screen using following code

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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
Ashish Joshi
  • 47
  • 1
  • 7

3 Answers3

3

Just convert to raw_input like this:

import ast
a = raw_input("Please enter a dictionary: ")
d = ast.literal_eval(a)
print d

Output:

{'a': 1, 'b': 2}

Explanation:

input() is just like doing eval(raw_input(....)) which at your case transforms the string to dict, ast.literal_eval() is expecting a string not a dict.

Also pay attention that at python 3.x there is no raw_input() since it's converted to input()

You can also refer to this post

Community
  • 1
  • 1
Kobi K
  • 7,743
  • 6
  • 42
  • 86
2

ast.literal_eval is used to convert string into dict object, from my guess you are inserting {'a':1,'b':1} (dict type) , then trying to use ast.literal_eval on it. It will give error as you are passing dict into function which accepts string) . If you want to take dictionary as string then use "{'a':1,'b':1}"

Code

>>> 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}
Zealous System
  • 2,080
  • 11
  • 22
1

I edited your code check difference.

import ast
a = input('Please enter a dictionary:')
d = ast.literal_eval(str(a))
print d
semira
  • 341
  • 3
  • 12