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 to perform multiple splits in one line?

I have a string in the following format:
x = "key1:value1 key2:value2 key3:value3"
How to write a one-line python command to have at the end a list of dictionaries with:

[
   {'key': 'key1', 'value': 'value1'},
   {'key': 'key2', 'value': 'value2'},
   {'key': 'key3', 'value': 'value3'}
]

Thanks for helping!

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 :

Single line python function to do this :

to_dict = lambda string: [{"key": k, "value": v} for k, v in (s.split(":") for s in string.split())]

Example use :

x = "key1:value1 key2:value2 key3:value3"
to_dict = lambda string: [{"key": k, "value": v} for k, v in (s.split(":") for s in string.split())]

print(to_dict(x))
# [{'key': 'key1', 'value': 'value1'}, 
# {'key': 'key2', 'value': 'value2'}, 
# {'key': 'key3', 'value': 'value3'}]
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