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!
>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'}]