Reputation: 5
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
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
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
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