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

Convert list to list of dictionaries: Python

I have the following sample list.

my_list = [('User2', 'String'), ('User2', 'Integer'), ('User3', 'String')]

I would like to append name and dtype in the list and would like to get a list of dictionaries similar to as follows.

my_new_list = [{'name':'User2', 'dtype':'String'}, {'name': 'User2', 'dtype':'Integer'}, {'name': 'User3', 'dtype':'String'}]

Here how I try it:

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

my_new_list = [] 
for i in my_list:
    my_new_list.append(i['name'])
    my_new_list.append(i['dtype'])

Anyone help with this?

>Solution :

You can use list comprehension:

my_list = [("User2", "String"), ("User2", "Integer"), ("User3", "String")]


my_new_list = [{"name": u, "dtype": s} for u, s in my_list]
print(my_new_list)

Prints:

[
    {"name": "User2", "dtype": "String"},
    {"name": "User2", "dtype": "Integer"},
    {"name": "User3", "dtype": "String"},
]
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