0

If I use literal_eval on some strings to get a dictionary, it works fine:

import ast string = '{123: True, 456: False}' In: ast.literal_eval(string) Out: {123: True, 456: False} 

But if the string has a string within it, I get an error:

string = '{123: Foo, 456: Bar}' In: ast.literal_eval(string) Out: ValueError: malformed node or string: <_ast.Name object at 0x7f7d5faae9e8> 

How can I keep strings in the second literal_eval?

3
  • 3
    Those aren't strings. In the code {123: Foo, 456: Bar}, Foo and Bar are python objects. Did you mean {123: "Foo", 456: "Bar"}? Commented Nov 22, 2019 at 21:53
  • @RishiG: They're not Python objects, they're interpreted as the names or identifiers of objects. Commented Nov 22, 2019 at 22:17
  • Similar question asked here: stackoverflow.com/questions/22235419/… Commented Nov 22, 2019 at 23:43

1 Answer 1

2

The example you gave, i.e.

{123: Foo, 456: Bar} 

does not contain strings. It contains identifiers Foo and Bar.

A correct string would rather look like:

{123: "Foo", 456: "Bar"} 

That's why AST module try to parse, does not see expected literal (number of string), and panics because it sees some identifier. Does that help?

P.S. Thanks @RishiG for pointing out redundant backslashes.

Sign up to request clarification or add additional context in comments.

6 Comments

You don't need the backslashes.
Technically, Foo and Bar are not literals, they are names - in the AST they're represented by Name objects. A literal is an expression which has a fixed value independent of any other code. en.wikipedia.org/wiki/Literal_(computer_programming)
I believe @snapcrack had strings inside (i.e., "if the string has a string inside"). Otherwise, you are right, Foo and Bar would be identifiers for some Python objects.
Foo and Bar are interpreted as Python names (aka identifiers), not literal values.
Thanks. This was honestly not a terribly well worded question on my part, but this definitely answers it as written.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.