簡體   English   中英

如何在 python 的列表內的字典中添加新的鍵和值?

[英]How to add new keys and values to dictionaries inside of a list in python?

如果這是一個基本問題,我很抱歉,但我怎樣才能在我的列表中的字典中添加一個新的鍵值對?

我想遍歷第一個列表,因此第一個列表值進入第一個列表字典,鍵為“數量”等等,請參見下面的 output。

Output:

[1, 2]
[{'id': 1, 'title': 'Tights 1', 'price': Decimal('200.00'), 'category_id': 1}, {'id': 2, 'title': 'Tights 2', 'price': Decimal('400.00'), 'category_id': 1}]

所需的 output:

[{'id': 1, 'title': 'Tights 1', 'price': Decimal('200.00'), 'quantity': 1, 'category_id': 1}, {'id': 2, 'title': 'Tights 2', 'price': Decimal('400.00'), 'quantity': 2, 'category_id': 1}]

要將新的密鑰對值添加到您的字典中,請執行以下操作:

dict['new_key'] = new_value

因此,調整您的代碼以創建一個新條目:

from decimal import Decimal
order_item_values = [{'id': 1, 'title': 'Tights 1', 'price': Decimal('200.00'), 'category_id': 1}, {'id': 2, 'title': 'Tights 2', 'price': Decimal('400.00'), 'category_id': 1}]


for item in order_item_values:
    item['quantity'] = item['id']
print(order_item_values)

循環遍歷列表並將元素添加到每個字典。

lst = list(item.values())
for i in range(len(lst)):
    lst[i]["quantity"] = i + 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM