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
  • 3,088
  • 1
  • 21
  • 33
Bhaskar
  • 333
  • 2
  • 12

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,884
  • 1
  • 10
  • 20
5

I would simply try

eval(a.replace('[', '{').replace(']', '}'))
Aemyl
  • 1,501
  • 1
  • 19
  • 34
  • 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
  • 47,830
  • 31
  • 106
  • 135
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
  • 191,408
  • 23
  • 240
  • 301
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,817
  • 1
  • 30
  • 48
Vishal R
  • 1,279
  • 1
  • 21
  • 27