首页 > 解决方案 > 在字典 Python 中访问列表中的值

问题描述

我在 django 中有一个表单集,它有多个表单,我将其保存为:

manifestData = form.cleaned_data

如果我print(manifestdata)返回以下内容:

[{'ProductCode': <Product: APPLES-1>, 'UnitQty': u'11', 'Price': u'11.00', 'Amount': u'121', 'DescriptionOfGoods': u'Washington Extra Fancy', 'Type': u'Cases', u'id': None, u'DELETE': False}, {'ProductCode': <Product: ORANGES-1>, 'UnitQty': u'1', 'Price': u'12.00', 'Amount': u'12', 'DescriptionOfGoods': u'SUNKIST ORANGES', 'Type': u'Cases', u'id': None, u'DELETE': False}]

我需要访问每个ProductCode并从列表中弹出它。所以我在我看来尝试以下方法:

...

for item in manifestData:
   x = manifestData.pop['ProductCode'] #this is highlighted in the error message

...

当我这样做时,我得到一个 TypeError 读取“需要一个整数”。谁能向我解释/我如何解决这个问题?

标签: pythondjango

解决方案


在您的代码中, manifestData 是一个字典列表。在您的 for 循环中,您正在遍历列表以获取每个字典,但随后您尝试从 manifestData 而不是 item 中弹出。

将您的代码更改为:

...

for item in manifestData:
   x = item.pop('ProductCode') #pop from item, not manifestData

...

注意:对于pop(),你需要使用括号,而不是方括号


推荐阅读