如何迭代字典列表中的键

2024-04-29 12:18:36 发布

您现在位置:Python中文网/ 问答频道 /正文

[为清晰和更正而编辑] 为提前发帖道歉。我搜集了并获得了一个json格式的响应。json代码如下所示:

{
"item":{
  "itemid":7041360985,
  :
  :
  : 
  "models":[
     {
        "itemid":7041360985,
        "status":1,
        "current_promotion_reserved_stock":0,
        "name":"",
        "promotionid":0,
        "price":2524141,
        "price_stocks":[
           {
              "model_id":65873300871,
              "stockout_time":0,
              "region":"MY",
              "rebate":"None",
              "price":4301287,
              "promotion_type":0,
              "allocated_stock":"None",
              "shop_id":449183886,
              "end_time":"None",
              "stock_breakdown_by_location":[
                 
              ],
              "item_id":11825286664,
              "promotion_id":0,
              "purchase_limit":"None",
              "start_time":"None",
              "stock":3
           }
        ],
        "current_promotion_has_reserve_stock":false,
        :
     }
  ],
  "min_purchase_limit":0,
  :
  }

我正试图从每种型号中获取名称和价格详细信息(如果有)。有时候,根本就没有模型,有时候会有4个

下面是我访问字典值的尝试,但我得到了以下结果:

type1=型号['name'] TypeError:字符串索引必须是整数

    def parse_data(self, response):
    resp = json.loads(response.body)

    for model in resp.get('models'):
        type1 = model['name']
            # 'type1price': model['price'],
        yield{
            'product': resp.get('item').get('name'),
            'upcoming_flash_sale': resp.get('item').get('name'),
            'rating': resp.get('item').get('item_rating').get('rating_star'),
            'review numbers': resp.get('item').get('cmt_count'),
            'viewcount': resp.get('item').get('view_count'),
            'likes': resp.get('item').get('liked_count'),
            'type1': type1,
            'location': resp.get('item').get('shop_location')
        }

产品详细信息,如喜好、审查编号等,可从关键“型号”外部获取。最后,我想将它们与从“模型”中获得的数据合并

如果有多个项模型字典(如果没有,则不破坏代码),如何循环遍历所有可用项


Tags: namenoneidjsongetmodeltimestock
2条回答

根据我对您输入和描述的理解,我认为您希望打印所有型号的名称和价格(可能没有)

此代码将打印所有模型(如果存在)的nameprice

import json
s = '''
{
   "item":{
      "itemid":7041360985,
      "models":[
         {
            "itemid":7041360985,
            "status":1,
            "current_promotion_reserved_stock":0,
            "name":"",
            "promotionid":0,
            "price":2524141,
            "price_stocks":[
               {
                  "model_id":65873300871,
                  "stockout_time":0,
                  "region":"MY",
                  "rebate":"None",
                  "price":4301287,
                  "promotion_type":0,
                  "allocated_stock":"None",
                  "shop_id":449183886,
                  "end_time":"None",
                  "stock_breakdown_by_location":[
                     
                  ],
                  "item_id":11825286664,
                  "promotion_id":0,
                  "purchase_limit":"None",
                  "start_time":"None",
                  "stock":3
               }
            ],
            "current_promotion_has_reserve_stock":false
         }
      ],
      "min_purchase_limit":0
   }
}
'''
j = json.loads(s)
if j['item'].get('models'):
    for i in j['item']['models']:
        name = i['name']
        price = i['price']
        print(f'Name: {name}\tPrice: {price}')
Name:   Price: 2524141

要将字典的键作为列表获取,可以执行以下操作:

dictionary.keys()

这将为您提供字典中的键列表,然后您可以对它们进行迭代

如果您不想查看键列表,只想对其进行迭代:

for i in dictionary:
    print(i) # Prints the dictionary keys
    print(dictionary[i]) # Prints the dictionary values

相关问题 更多 >