user765443
user765443

Reputation: 1892

How to convert string to dictionary into python

How can I convert a string

s = "1:5.9,1p5:7,2:10,4:18,8:40"

to a dictionary like this?

s = { '1':'5.9','1p5':'7','2':'10','4':'18','8':40'}

Upvotes: 1

Views: 107

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

Use dict() and str.split:

>>> s = "1:5.9,1p5:7,2:10,4:18,8:40"
>>> dict(item.split(':') for item in s.split(','))
{'1': '5.9', '8': '40', '2': '10', '4': '18', '1p5': '7'}

Using a dict-comprehension:

>>> {k:v for k, v in (item.split(':') for item in s.split(','))}
{'1': '5.9', '8': '40', '2': '10', '4': '18', '1p5': '7'}

Upvotes: 5

Related Questions