Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i convert a list of strings into a list of dictionaries in python?

I’d like to convert a list of structurally similar strings into a list of dictionaries.

Example list of strings:

list_of_strings = [
'ID payment_method email issue_date payment_date amount currency',
'ID payment_method email issue_date payment_date amount currency',
'ID payment_method email issue_date payment_date amount currency',
...
]

Each snippet of information is sperated by a whitespace inside the strings themselves.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Desired output:

resulting_list_of_dicts = [
dict_1 = {"ID": "id1", "payment_method": "paymentmethod1", "e_mail": "email1", "payment_date": "paymentdate1", "amount": "amount1", "currency": "currecny1"},
dict_2 = {"ID": "id2", "payment_method": "paymentmethod2", "e_mail": "email1", "payment_date": "paymentdate2", "amount": "amount2", "currency": "currecny2"},
...
]

I’ve tried using the string split function, by I am running into trouble when trying to append the sub strings to a dict.

>Solution :

Loop over each line in the string list.

Use split() to get each separate part.

Build a new dictionary from those parts and append it to another list.

list_of_dicts = [] 
for s in list_of_strings:
    parts = s.split()
    list_of_dicts.append({
        'id': parts[0],
        'payment_method': parts[1],
        ... and so on
    })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading