0

Let's assume I have list, and have turned it into a string (to use it as a dictionary key for example). Is there a way to get the list back from the string? This code snippet should illustrate what I want:

list_str = str([1,2,3])
my_list = some_operation(list_str)

such that the variable my_list contains the list [1,2,3]

Any help would be appreciated!

Nicolas
  • 85
  • 2
  • 6

2 Answers2

1

You could use ast.literal_eval(list_str) but the real question is why did you convert it into a string in the first place? You could have converted it to a tuple (immutable and hashable) to use as a dict key

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
-3

It's not a good idea, but you can try:

# list_str holds your list in a string
vals = list_str[1:-1]
l = [int(x.strip()) for x in vals.split(",")]
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292