Answer the question
In order to leave comments, you need to log in
How to sort a string into a dictionary?
There is a line
Name1: Some1 Name2: Some2 Name3: Some3
And so on
How to sort it into a dictionary by python code?
Answer the question
In order to leave comments, you need to log in
Here I scribbled without regexps:
my_string = 'somefalsename Name1: Some1 somesome1 Name2: Some2 Name3: Some3 Name4:'
def dict_from_string(my_string):
my_list = my_string.split()
my_dict = {}
key = ''
value = ''
while len(my_list) > 0:
next_element = my_list.pop()
if ':' in next_element:
key = next_element.replace(':','')
my_dict.update({key: value})
key = ''
value = ''
else:
value = ' '.join([next_element, value]).strip()
return my_dict
print(dict_from_string(my_string))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question