简体   繁体   中英

Accessing Values Within A List Within A Dict Python

I have a formset in django which has multiple forms which I am saving as:

manifestData = form.cleaned_data

If I print(manifestdata) it returns the below:

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

I need to access each ProductCode and pop it from the list. So I am trying the below in my view:

...

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

...

When I do this I get a TypeError reading that "an integer is required". Can anyone explain that to me / how I can navigate this issue?

In your code, manifestData is a list of dictionary. In your for loop, you are looping through the list to get each dictionary, but then you try to pop from manifestData, rather than item.

Change your code to be:

...

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

...

Note: For pop(), you need to use parentheses, not brackets

1.you need to pop from item rather than manifestData.
2.use () bracket while using pop function for dictionary instead of [].

for item in manifestData:
   x = item.pop('ProductCode') #to pop from dictionary you need to use this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM