簡體   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