how to perform multiple splits in one line?

Question:

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!

Asked By: yoka791

||

Answers:

Use python string split()

[{'key':x.split(':')[0], 'value':x.split(':')[1]} for x in x.split()]

which gives you expected output

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

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'}]
Answered By: curlybracketenjoyer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.