使用相同的关键字名称[python]插入字典



尝试从字典列表创建新字典;那些字典有重复的关键字名称,我需要将这些带有值的关键字附加到一个新的空字典中

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={}

我trird,但它总是采用最后一个字典值

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

你似乎想要一个嵌套的dict。在你的情况下,你应该使用一个dict列表,但仍然可以通过添加顶级键来制作一个嵌套dict:

test={}
for i, data in enumerate(items):
test[str(i)] = { 'actual_batch_qty': data['actual_batch_qty'], 'amount': data['base_amount'] }

print(test) 

输出:

{'0': {'actual_batch_qty': 5, 'amount': 80.0}, '1': {'actual_batch_qty': 7, 'amount': 100}}

循环通过:

for k,v in test.items():
#stuff
pass

UPD:问题已编辑,因此下面的答案与无关

使用defaultdict

from collections import defaultdict

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 = defaultdict(list)
for data in items:
test['actual_batch_qty'].append(data['actual_batch_qty'])
test['weigth'].append(data['total_weight'])
print(test) 

最新更新