I. Domshchikov I. Domshchikov - 2 years ago 85
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 Source

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}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download