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'}
Use dict() and str.split:
dict()
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'}
Sign up using Google
Sign up using Facebook
Sign up using Stack Exchange
By posting your answer, you agree to the privacy policy and terms of service.
tagged
asked
today
viewed
50 times
active