Home > Back-end >  How to transform a tuple into a dictionary?
How to transform a tuple into a dictionary?

Time:12-30

I need help with a list of tuples.

I have the next list:

list = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]

I need to transform a tuple into a dictionary and get the next result:

list = [{'name':'x1', 'amount':'10'}, {'name':'x2', 'amount':'15'}, 
        {'name':'x3', 'amount':'35'}, {'name':'x4', 'amount':'55'}]

CodePudding user response:

You also use dict() constructor inside a list comprehension:

out = [dict(zip(['name','amount'], tpl)) for tpl in lst]

or equivalently, you can also use dict() constructor inside map:

out = list(map(lambda tpl: dict(zip(['name','amount'], tpl)), lst))

Output:

[{'name': 'x1', 'amount': '10'},
 {'name': 'x2', 'amount': '15'},
 {'name': 'x3', 'amount': '35'},
 {'name': 'x4', 'amount': '55'}]

CodePudding user response:

Try a nested dictionary comprehension.

list_of_tuples = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]
result = [{'name': name, 'amount': amount} for name, amount in list_of_tuples]

This is equivalent to the more verbose (but perhaps more readable)

result = []
for name, amount in list_of_tuples:
    d = {'name': name, 'amount': amount}
    result.append(d)

CodePudding user response:

list = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]

_list = []
for i in list:
    _list.append({"name":i[0],"amount":i[1]})

print(_list)

CodePudding user response:

this worked for me:

dic={}
list2=[]
for i in range(len(list)):
   dic[list[i][0]]=list[i][1]
   or 
   dic2={}
   dic2['name']=list[i][0]
   dic2['amount']=list[i][1]
   list2.append(dic2)
  • Related