Home > Software engineering >  Convert list to list of dictionaries: Python
Convert list to list of dictionaries: Python

Time:08-07

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:

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

Anyone help with this?

CodePudding user response:

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"},
]

CodePudding user response:

Hope this can help.

my_list = [('User2', 'String'), ('User2', 'Integer'), ('User3', 'String')]
my_new_list = []
for i in my_list:
    my_new_list.append({'name':i[0],'dtype':i[1]})
print(my_new_list)
  • Related