1

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'}
1
  • I could not get any breakthrough which help me to fix this thing Commented Aug 23, 2013 at 13:30

1 Answer 1

5

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'}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.