Home > database >  Building a list of dict from list of tuples
Building a list of dict from list of tuples

Time:02-24

I have the following tuple

[('A', 38, 132.0, 132.0), ('V', 22, 223.0, 223.0)]

I would like to loop through it and create a dict that look like this:

[{'symbol': 'A', 'sumshares': 38, 'avgprice': 132.0, 'purchase_p': 132}, {'symbol': 'V', 'sumshares': 22, 'avgprice': 223.0, 'purchase_p': 223.0}]

Tried for few days to find the correct way to do this without success:(

Thanks for your help.

CodePudding user response:

You can use list comprehension. Why this works is that first the list comprehension destuctures each tuple in the original list and then the destructured variables (a, b, c, and d) are inserted into the dictionary.

original = [('A', 1, 2, 3), ('X', 3, 4, 5)]
dictionary = [{'a': a, 'b': b, 'c': c, 'd': d} for a, b, c, d in original]

And with looping, you could use destructuring to get the values and append the list with dictionaries:

newlist = []

for row in original:
    a, b, c, d = row
    
    newlist.append({'a': a, 'b': b, 'c': c, 'd': d})

print(newlist)

CodePudding user response:

lst = [('A', 38, 132.0, 132.0), ('V', 22, 223.0, 223.0)]
keys = ('symbol', 'sumshares', 'avgprice','purchase_p')
dlist = []

for l in lst:
    dlist.append(dict(zip(keys, l)))

print(dlist)

output

[{'symbol': 'A', 'sumshares': 38, 'avgprice': 132.0, 'purchase_p': 132.0}, {'symbol': 'V', 'sumshares': 22, 'avgprice': 223.0, 'purchase_p': 223.0}]

CodePudding user response:

data=[('A', 38, 132.0, 132.0), ('V', 22, 223.0, 223.0)]
keys=['symbol','sumshares','avgprice','purchase_p']
mydict=[dict(zip(keys,dat)) for dat in data ]

print(mydict)

output
[{'symbol': 'A', 'sumshares': 38, 'avgprice': 132.0, 'purchase_p': 132.0}, {'symbol': 'V', 'sumshares': 22, 'avgprice': 223.0, 'purchase_p': 223.0}]

  • Related