python - 在字典 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 读取“需要一个整数”。谁能向我解释/我如何解决这个问题?
解决方案
在您的代码中, manifestData 是一个字典列表。在您的 for 循环中,您正在遍历列表以获取每个字典,但随后您尝试从 manifestData 而不是 item 中弹出。
将您的代码更改为:
...
for item in manifestData:
x = item.pop('ProductCode') #pop from item, not manifestData
...
注意:对于pop(),你需要使用括号,而不是方括号
推荐阅读
- android - 限制您的 android 活动可以从其他活动访问
- python - 使用 .txt 中的 numpy 读取 4D 数组
- flutter - 如何在 ListTileTheme 中使用形状?
- java - 添加“cors disable”时,安全配置对所有匹配器应用身份验证
- c# - EF6:参数“nameOrConnectionString”不能为空、空或仅包含空格
- r - 查找整个数据帧的分位数
- javascript - A* 寻路,路径未显示
- java - kafka流:同一主题中的不同对象
- asp.net - 我们如何使用 YAML 从构建中排除项目?
- angular - 如何在 @angular/cli 库中包含 mqtt.js