Reputation: 1892
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
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