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

convert string to dictionary in python (passing dict as plain str)

I have a string

test_string = "{Team A: [service1, service2], Team B: [service3, service4], Team 3: [service5, service6] }"

I want to know a way to convert this into a dictionary in python

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 :

The yaml library is able to load this. It will turn all your items into strings, unless they are parseable in python:

import yaml

test_string = "{Team A: [service1, service2], Team B: [service3, service4], Team 3: [service5, service6] }"

parsed_dict = yaml.safe_load(test_string)
print(parsed_dict)

Outputs:

{'Team A': ['service1', 'service2'], 'Team B': ['service3', 'service4'], 'Team 3': ['service5', 'service6']}

Here is another example of what it may parse:

>>> yaml.safe_load("{a b c : [123, 99.0, a string, another]}")
{'a b c': [123, 99.0, 'a string', 'another']}

You should be aware that YAML (and so parsing with YAML) is a very complicated format that can have a lot of unintended effects. If possible you should find out if you can output JSON or some other serialised data from your Azure DevOps pipeline.

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