Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I convert a string to dictionary in a manner where I have to extract key and value from same string

I need to convert string to dictionary in a manner for example

str1 = "00001000-0009efff : a 00100000-656b2fff : b"

Output what I require is

dict1 = {'a':['00001000','0009efff'], 'b':['00100000','656b2fff']}

Note: str1 can have many more such c, d, e with range.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do it with a regex:

import re

pattern = r'([\w\-]+) : ([a-z])'
out = {m[1]: m[0].split('-') for m in re.findall(pattern, str1)}

Explanation of the regex:

  • match combination of alphanumeric characters and dashes [\w-]+
  • followed by a space, a colon and a space _:_
  • followed by a character [a-z]

The groups are catching your relevant infos.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading