nickv1989
nickv1989

Reputation: 5

How to convert long string into a dictionary by splitting on line breaks and colons

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

Upvotes: 0

Views: 210

Answers (3)

Jordan
Jordan

Reputation: 617

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}

[Update] Alternative approach by Rabinzel:


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

metadata_dict = dict(tuple(map(str.strip, string.split(':'))) for string in metadata.split('\n'))

Upvotes: 1

René
René

Reputation: 4827

This oneliner should work for you:

{x.split(':')[0].strip():x.split(':')[1].strip() for x in metadata.split('\n')}

Output:

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

Upvotes: 0

lroth
lroth

Reputation: 367

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

Upvotes: 0

Related Questions