简体   繁体   中英

Python: how to process list of dicts

I am trying to store discount codes and amounts from this json. I am not going to know how many dicts will be in the list.

  "discount_codes":[
     {
        "code":"STUDENT",
        "amount":"10.00",
        "type":"percentage"
     },
     {
        "code":"TEACHER",
        "amount":"15.00",
        "type":"percentage"
     }
  ]

I am trying this, but it does not work:

for codes, x in enumerate(discount_codes):
    discount_code = codes['x']['code']
    discount_amount = codes['x']['amount']
    print (discount_code)
    print (discount_amount)


Enumerate on list return the index and value and in your case value is a dictionary, get the value from dictionary as below code:

for index, value in enumerate(discount_codes):
print(index)
print(value)
discount_code = value['code']
discount_amount = value['amount']
print(discount_code)
print(discount_amount)
#print (discount_code)
#print (discount_amount)

Added the complete code and execution as an image: 在此处输入图像描述

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