简体   繁体   中英

Building a list of dict from list of tuples

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.

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)
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}]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM