[英]Python: how to process list of dicts
I am trying to store discount codes and amounts from this json.我正在尝试存储此 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:将完整的代码和执行添加为图像:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.