Home > Back-end >  How to convert long string into a dictionary by splitting on line breaks and colons
How to convert long string into a dictionary by splitting on line breaks and colons

Time:07-30

I have the following string that I have created in python:

metadata = """Passengerid: string
Name: string
sex: categorical
Fare: numeric
Fareclass: numeric"""

I would like to create a for loop that unpacks this string and creates a dictionary.

My desired output would be:

dct = 
{'Name': 'string',
'sex': 'categorical',
'Fare': 'numeric',
'Fareclass': 'numeric'
}

My instinct to get started is something like:

metadata.split('\n')

Which would yield the following list but is not creating anything that could be obviously turned into a dictionary:

['Passengerid: string',
 'Name: string',
 'sex: categorical',
 'Fare: numeric',
 'Fareclass: numeric']

CodePudding user response:

Try this:

metadata = """Passengerid: string
Name: string
sex: categorical
Fare: numeric
Fareclass: numeric"""

metadata = [tuple(m.replace(' ', '').split(':')) for m in metadata.split('\n')]
metadata_dict = {k:v for (k, v) in metadata}

CodePudding user response:

using the input data from metadata (triple quoted string) we can do:

my_dict = {}
for line in metadata.splitlines():
    k, v = line.split(":")
    my_dict.update({k: v})
  • Related