1

I have a string: x = '[{'id': 35, 'name': 'Comedy'}, {'id': 53, 'name': 'Thriller'}]'

I want to convert this string into a list:x = [{'id': 35, 'name': 'Comedy'}, {'id': 53, 'name': 'Thriller'}]

I tried doing this: x = list(x)

but this returns all the characters separated by a comma. ['[', '{', "'", 'i', 'd', "'", ':', ' ', '3', '5', ',', ' ', "'", 'n', 'a', 'm', 'e', "'", ':', ' ', "'", 'C', 'o', 'm', 'e', 'd', 'y', "'", '}', ']']

x = list(x)

1 Answers1

3

When you do list(x) you get a list of individual characters of the string.

Instead you can use ast.literal_eval for this (You could have used json.loads but you cannot since the string contains single quotes)

In [5]: import ast                                                                                                                                                                     

In [6]: x = "[{'id': 35, 'name': 'Comedy'}, {'id': 53, 'name': 'Thriller'}]"                                                                                                           

In [7]: ast.literal_eval(x)                                                                                                                                                            
Out[7]: [{'id': 35, 'name': 'Comedy'}, {'id': 53, 'name': 'Thriller'}]
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40