0

is there any method to converts python dictionary with strings to python dictionary with corresponding integer arrays

Dictionary with String Arrays:

 {1: '[8, 9, 10, 11, 12, 13, 14, 15, 16]',
 2: '[17, 18, 19, 20, 21, 22, 23]',
 3: '[1, 2, 3, 4, 5, 6, 7]',
 4: '[24, 25, 26]'}

Converted to Dictionary with corresponding Integer Arrays:

{1: [8, 9, 10, 11, 12, 13, 14, 15, 16],
 2: [17, 18, 19, 20, 21, 22, 23],
 3: [1, 2, 3, 4, 5, 6, 7],
 4: [24, 25, 26]}
Chandu
  • 3
  • 1

1 Answers1

0

Using ast.literal_eval we can loop over the dictionary and "cast" the string into their literals:

>>> import ast
>>> x =  {1: '[8, 9, 10, 11, 12, 13, 14, 15, 16]',
...  2: '[17, 18, 19, 20, 21, 22, 23]',
...  3: '[1, 2, 3, 4, 5, 6, 7]',
...  4: '[24, 25, 26]'}
>>>
>>> {k: ast.literal_eval(v) for k,v in x.items()}
{1: [8, 9, 10, 11, 12, 13, 14, 15, 16], 2: [17, 18, 19, 20, 21, 22, 23], 3: [1, 2, 3, 4, 5, 6, 7], 4: [24, 25, 26]}
Hampus Larsson
  • 3,050
  • 2
  • 14
  • 20