【发布时间】:2021-04-14 11:47:27
【问题描述】:
试图从字典列表中创建一个新字典;那些字典有重复的键名我需要将这些键与值附加到一个新的空字典
items=[
{
'actual_batch_qty': 5,
'actual_qty': 6,
'allow_zero_valuation_rate': 4,
'amount': 80.0,
'base_amount': 80.0,
},
{
'actual_batch_qty': 7,
'actual_qty': 2,
'allow_zero_valuation_rate': 5,
'amount': 140,
'base_amount':100,
}
]
test={}
我很担心,但它总是采用最后一个字典值
for data in items:
test['actual_batch_qty'] = data['actual_batch_qty']
test['amount']=data['base_amount']
print(test)
输出:
{'actual_batch_qty': 7, 'amount': 100}
预期输出:
[{'actual_batch_qty': 5, 'amount': 80.0},{'actual_batch_qty': 7, 'amount': 100}]
【问题讨论】:
-
预期的输出不是有效的 Python
-
@gold_cy 为什么无效?
-
因为你所描述的是一个充满字典的集合,这是无效的,因为字典不是可散列的
标签: python dictionary