F
F
flex7r2020-12-30 22:34:32
Algorithms
flex7r, 2020-12-30 22:34:32

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

3 answer(s)
A
Alan Gibizov, 2020-12-30
@phaggi

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))

D
Dr. Bacon, 2020-12-30
@bacon

split

A
aRegius, 2020-12-30
@aRegius

import re

keys_values_list = re.split(r'[:\s]\s*', string_data)
keys, values = keys_values_list[::2], keys_values_list[1::2]
dict_data = dict(zip(keys, values))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question