【问题标题】:how do i iterate over keys in a list of dictionaries我如何遍历字典列表中的键
【发布时间】:2021-10-16 09:29:37
【问题描述】:

[为清晰和更正而编辑] 为早早匆忙的帖子道歉。我 scraped 并获得了 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 = 型号['名称'] 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')
        }

产品详细信息,例如喜欢、评论编号等,是从关键“型号”之外获得的。最后,我想将它们与从“模型”中获得的数据合并。

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

【问题讨论】:

  • 似乎有一个顶级键 'item' 您的代码没有处理。试试resp['item']['models']
  • 对于给定的代码,你将如何获得'type1': resp.get('models')[0]['name'], TypeError: 'NoneType' object is not subscriptable.?您从未在代码中使用过resp.get('models')[0]['name'] 表达式。你使用的是model[0]['name']。共享给定代码的输出回溯,以便我们查看哪一行是错误的
  • 另外模型变量是字典而不是列表,所以模型[0]会给出关键错误
  • 只需删除[0]model 是一个字典,而不是一个列表。也就是说,yield 看起来很奇怪。您可能希望显示您的确切预期输出,以便其他人可以帮助指导您。
  • 这不会解决问题,因为我认为模型是 Nonetype。 OP 应该共享原始代码的回溯

标签: python json web-scraping


【解决方案1】:

要将字典的键作为列表获取,您可以这样做:

dictionary.keys()

这将为您提供字典中的键列表,然后您可以遍历它们。

如果您不想要键列表而只想遍历它们:

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

【讨论】:

  • 抱歉!我尝试了很多方法,这是一个匆忙的帖子。我弄乱了代码和输出。我编辑了我的帖子以更好地反映我的问题。谢谢!
【解决方案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

【讨论】:

  • 谢谢!那行得通!但是我如何做产量而不是打印?因为我想将它与从该特定产品收集的其他数据一起保存为 csv。
猜你喜欢
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 2012-07-07
  • 2023-03-14
  • 2020-05-16
  • 2012-07-04
  • 2019-11-29
相关资源
最近更新 更多