I. Domshchikov I. Domshchikov - 7 months ago 19
Python Question

Best way to convert str 'key: value\r\nkey:value\r\n' to dict, python

I have the following string

"first: 1\r\nsecond: 2\r\n"
, I want to receive following dict
{'first': 1, 'second': 2}
.

How can I do that?

Answer

You can use regular expressions:

import re

matches = re.findall(r'(\w+):\s*(\d+)', my_string)
# [('first', '1'), ('second', '2')]

matches = [(x[0], int(x[1])) for x in matches]
# [('first', 1), ('second', 2)]

d = dict(matches)
# {'first': 1, 'second': 2}