从元组列表构建字典列表

Building a list of dict from list of tuples

我有以下元组

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

我想遍历它并创建一个如下所示的字典:

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

尝试了几天没有成功找到正确的方法:(

感谢您的帮助。

您可以使用列表理解。这样做的原因是首先列表理解解构了原始列表中的每个元组,然后将解构的变量(a、b、c 和 d)插入到字典中。

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]

通过循环,您可以使用解构来获取值并将列表附加到字典中:

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)

输出

[{'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)

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