Convert list to list of dictionaries: Python

Question:

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?

Asked By: Hiwot

||

Answers:

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"},
]
Answered By: Andrej Kesely

You can try this:

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)
Answered By: Rickyxrc

test_list = ["John", 3, "Jack", 8, "Jane", 10]
key_list = ["name", "number"]
n = len(test_list)
res = []
for idx in range(0, n, 2):
    res.append({key_list[0]: test_list[idx], key_list[1] : test_list[idx + 1]})
print(str(res))

Answered By: Anthony Orlando
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.