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

时间:2020-07-25 21:13:29

标签: python

很抱歉,这是一个基本问题,但是如何在列表中的字典中添加新的键值对?

我想遍历第一个列表,以便第一个列表值使用键“ quantity”进入第一个列表字典,依此类推,请参见下面的输出。

输出:

def first_positive(num):
    i=0    # i is the current index
    while(i<len(num) and num[i]<=0):  # i<len(num) means run the while loop until there are elements in the num list
        i+=1
    if i==len(num):   # when there are no positive elements present in the list
        return "No positive element found"
    else:
        return num[i]
print(first_positive([-2,-3,5,10]))     # prints 5
print(first_positive([-2,-3,-5,10]))    # prints 10
print(first_positive([-2,-3,-5,-10]))   # prints No positive element found

所需的输出:

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

浏览列表,然后将元素添加到每个字典中。

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