我正在处理一些JSON并在Python中解析它我有这个部分我似乎无法弄清楚它的语法。所以这是我的JSON:
u'line_items':[
{
u'product':{
u'weight':0.5,
u'regular_price':u'$40.00',
u'name_short':u'Name',
u'currency':u'USD',
},
{
u'product':{
u'weight':None,
u'regular_price':u'$17.00',
u'name_short':u'Map of the World Jumbo Puzzle',
u'currency':u'USD',
}
]
有时line_items列表中有多个产品。在line_items中迭代产品dicts的语法是什么?我正在尝试
for j in i['line_items']
product = j['product']
但它仅适用于第一个产品。此外,i
还可以作为包含line_items
的较大字典的枚举器。
答案 0 :(得分:0)
由于您没有向我们提供完整的数据结构,我只是猜测,但是,......您只有一个级别的列表。枚举它以获得产品序列。
for item in i['line_items']:
product = item['product']
weight = product['weight']
# sanity check
print("product: %s, weight: %s" % (product['name_short'], weight))
答案 1 :(得分:-1)
迭代产品:
for product in i['line_items']:
# prints single products
print product
或者,如果您需要产品索引(以下示例中为index_in_list
):
for index_in_list in range(len(i['line_items'])):
# prints single products
print i['line_items'][index_in_list]
迭代单个产品的密钥:
for product_key in i['line_items'][index_in_list]:
# prints product info
print product_key, '-', i['line_items']['product'][product_key]
或者更容易:
for product_key, product in i['line_items'][index_in_list].iteritems():
# still has access to 'product_key' if you want to modify it.
print product_key, '-', product