3

How can I convert a str representation of the list, such as the below string into a dictionary?

a = '[100:0.345,123:0.34,145:0.86]'

Expected output :

{100:0.345,123:0.34,145:0.86}

First tried to convert the string into a list using ast.literal_eval. But it's showing an error as : invalid syntax

Vikas Periyadath
  • 2,930
  • 1
  • 17
  • 28
Bhaskar
  • 303
  • 2
  • 11

5 Answers5

8

It's showing as invalid syntax because it has the wrong brackets, so you could do

ast.literal_eval(a.replace("[","{").replace("]", "}"))

Or alternatively parse the string yourself in a dictionary comprehension

{x.split(":")[0]: x.split(":")[1] for x in a[1:-1].split(",")}

and if as mentioned there are [ or ] elsewhere in your string the following may be more robust

ast.literal_eval("{" + a[1:-1] +"}")
Sven Harris
  • 2,714
  • 1
  • 8
  • 17
5

I would simply try

eval(a.replace('[', '{').replace(']', '}'))
Aemyl
  • 1,327
  • 1
  • 20
  • 31
  • 1
    [Why is using eval a bad practice](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) - ast.literal_eval is safer. – Patrick Artner Sep 27 '18 at 05:52
  • 1
    It depends on where `a` comes from ... if it is not from user input, it might be a pain to import `ast` just for this purpose – Aemyl Sep 27 '18 at 05:59
1

To convert to a dict:

Code:

data = '[100:0.345,123:0.34,145:0.86]'

new_data = dict(y.split(':') for y in (x.strip().strip('[').strip(']')
                                       for x in data.split(',')))

print(new_data)

Or if you need numbers not strings:

new_data = dict((map(float, y.split(':'))) for y in (
    x.strip().strip('[').strip(']') for x in data.split(',')))

Results:

{'100': '0.345', '123': '0.34', '145': '0.86'}

{145.0: 0.86, 123.0: 0.34, 100.0: 0.345}
Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125
0

Translate brackets to braces, literal_eval.

rebracket = {91: 123, 93: 125}
a = '[100:0.345,123:0.34,145:0.86]'
literal_eval(a.translate(rebracket))
Amadan
  • 179,482
  • 20
  • 216
  • 275
0

Given a string representation of a dict:

a = '[100:0.345,123:0.34,145:0.86]'

Ignore the containing braces [..], and break up the elements on commas:

a = a[1:-1].split(",")

For each element, separate the key and value:

d1 = [x.split(":") for x in a]

Reconstitute the parsed data as a dict:

d2 = { int(k[0]) : float(k[1]) for k in d1}
bschlueter
  • 3,422
  • 27
  • 45
Vishal R
  • 1,129
  • 17
  • 24