繁体   English   中英

我遍历字典列表时如何从嵌套字典中提取特定值?

[英]How do I extract a specific value from a nested dictionary as I iterate through a list of dictionaries?

我正在使用CNN,需要从json文件中的URI抓取一些图像,但请使其与相应的ID相关联。 我有一个看起来像这样的json文件。 我想遍历每个产品并提取“ id”,并从“ image_uris”中提取“大” uri。

[{
  "product_type": "widget",
  "id": "1744556-ghh56h-4633",
  "manufacture_id": "AAB4567",
  "store_ids": [416835, 456145],
  "name": "Best Widget",
  "origin": "US",
  "manufactured": "2018-08-26",
  "uri": "https://bobswidgets.com/best_widget",
  "image_uris": {
    "small": "https://bobswidgets.com/small/best_widget_sm.jpg",
    "normal": "https://bobswidgets.com/medium/best_widget_md.jpg",
    "large": "https://bobswidgets.com/large/best_widget_lg.jpg",
  },
  "manufacture_cost": "12.50",
},
{
  "product_type": "widget",
  "id": "0956786-dje596-3904",
  "manufacture_id": "BCD13D",
  "store_ids": [014329, 40123],
  "name": "Best Widget2",
  "origin": "US",
  "manufactured": "2018-10-03",
  "uri": "https://bobswidgets.com/best_widget_2",
  "image_uris": {
    "small": "https://bobswidgets.com/small/best_widget2_sm.jpg",
    "normal": "https://bobswidgets.com/medium/best_widget2_md.jpg",
    "large": "https://bobswidgets.com/large/best_widget2_lg.jpg",
  },
  "manufacture_cost": "13.33",
}]

然后,我想像这样将它们放入自己的字典中。 除非有更好的主意,至少这是我想做的:

[{"1744556-ghh56h-4633" : "https://bobswidgets.com/large/best_widget_lg.jpg"}, {"0956786-dje596-3904", "https://bobswidgets.com/large/best_widget2_lg.jpg"}]

我的最终选择是在这些URI处获取图像,并使用“ id”作为图像名称保存它们,如下所示:

1744556-ghh56h-4633_lg.jpg
0956786-dje596-3904_lg.jpg

最终,这些图像将用于CNN,就像我之前提到的那样。 识别出图像后,可以执行查找并从json文件返回所有其他值。

到目前为止,这里是我用来提取所需数据的代码。 它可以很好地捕获“ id”,但可以捕获所有图像uri。 我只想要“大” uri。

import ujson as json

with open('product.json', 'r') as f:
    prod_txt = f.read()

prod_dict = json.loads(prod_txt)

id = []
uris = []

    for dictionary in prod_dict:
        id.append(list(dictionary.values())[1])
        if isinstance(dictionary, dict):
            uris.append(list(dictionary.values())[8])

我已经进行了各种尝试,以单挑出“大” uri而没有成功。不确定如何使用嵌套字典来做到这一点而不会引发错误。 我敢肯定这很简单,但我仍然是一名业余编码员。

使用list推导,这可以非常简单地完成

In [106]: img_ids = [{d['id']: d['image_uris']['large']} for d in prod_dict]

In [107]: img_ids
Out[107]:
[{'1744556-ghh56h-4633': 'https://bobswidgets.com/large/best_widget_lg.jpg'},
 {'0956786-dje596-3904': 'https://bobswidgets.com/large/best_widget2_lg.jpg'}]

请注意,这假设list中的每个dictimage_uris始终有一个id和一个large值。 如果这些不存在,您将得到一个KeyError

如果是这种情况,则必须像这样利用dict.get

# Adding new entry without 'image_uris' dict
In [110]: prod_dict.append({'id': 'new_id'})

In [111]: img_ids = [{d['id']: d.get('image_uris', {}).get('large', 'N/A')} for d in prod_dict]

In [112]: img_ids
Out[112]:
[{'1744556-ghh56h-4633': 'https://bobswidgets.com/large/best_widget_lg.jpg'},
 {'0956786-dje596-3904': 'https://bobswidgets.com/large/best_widget2_lg.jpg'},
 {'new_id': 'N/A'}]

您对product.json文件所做的编辑仍无法使其成为有效的JSON,因此我改用了以下内容:

[
  {
    "product_type": "widget",
    "id": "1744556-ghh56h-4633",
    "manufacture_id": "AAB4567",
    "store_ids": [
      416835,
      456145
    ],
    "name": "Best Widget",
    "origin": "US",
    "manufactured": "2018-08-26",
    "uri": "https://bobswidgets.com/best_widget",
    "image_uris": {
      "small": "https://bobswidgets.com/small/best_widget_sm.jpg",
      "normal": "https://bobswidgets.com/medium/best_widget_md.jpg",
      "large": "https://bobswidgets.com/large/best_widget_lg.jpg"
    },
    "manufacture_cost": "12.50"
  },
  {
    "product_type": "widget",
    "id": "0956786-dje596-3904",
    "manufacture_id": "BCD13D",
    "store_ids": [
      "014329",
      "40123"
    ],
    "name": "Best Widget2",
    "origin": "US",
    "manufactured": "2018-10-03",
    "uri": "https://bobswidgets.com/best_widget_2",
    "image_uris": {
      "small": "https://bobswidgets.com/small/best_widget2_sm.jpg",
      "normal": "https://bobswidgets.com/medium/best_widget2_md.jpg",
      "large": "https://bobswidgets.com/large/best_widget2_lg.jpg"
    },
    "manufacture_cost": "13.33"
  }
]

因此,无需考虑这一点,并假设您自己能够以某种方式完成此操作,则可以使用称为字典显示的东西来创建所需的字典,该显示列表理解非常相似。

import json
from pprint import pprint

filename = 'product.json'

with open(filename, 'r') as f:
    prod_txt = f.read()
    prod_list = json.loads(prod_txt)

result_dict = {product['id']: product['image_uris']['large']
                for product in prod_list}

pprint(result_dict)

输出:

{'0956786-dje596-3904': 'https://bobswidgets.com/large/best_widget2_lg.jpg',
 '1744556-ghh56h-4633': 'https://bobswidgets.com/large/best_widget_lg.jpg'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM