I have a list of dictionaries containing data on products. Each product has one image url. The data looks very much like below. I wrote the code below and it works as intended but I'm pretty sure this can be done in one step by retrieving the url right from items_dicts. I instead used a dictionary comprehension to return a new dict item_dict given a specific uniq_id and then proceeded to retrieve the url from item_dict.
Data:
items_dicts = [
{
"uniq_id":"123987",
"sku":"123",
"name":"ABC",
"cat":"DEF",
"cat_tree":"A|B|C",
"image_urls":"http://sitecom/image1.tif"
},
{
"uniq_id":"987123",
"sku":"987",
"name":"GHI",
"cat":"JKL",
"cat_tree":"Z|Y|X",
"image_urls":"http://sitecom/img/image2.tif"
}
]
Code:
# import modules
import urllib.request
from PIL import Image
# Return a specific product dict and assign it to item_1
item_dict = {i['uniq_id'] : i for i in items_dicts}
item_1 = item_dict.get('987123', 'None')
# Retrieve img url from item_1 dict
# And save it as item_img.png
urllib.request.urlretrieve(item_1.get('image_urls'),"img.png")
# Open item img and display it
item_img = Image.open("img.png")
item_img.show()
CodePudding user response:
Edit:
To get one specific value from your list of dicts, for example where uniq_id is 123987, you can use the following:
[x['image_urls'] for x in items_dicts if x['uniq_id'] == '123987']
I'm not sure about your exact intention, but you can get easily get a list of all URLs from your list of dicts by using a list comprehension:
[x['image_urls'] for x in items_dicts]
Giving you:
['http://sitecom/image1.tif', 'http://sitecom/img/image2.tif']
You can then take this list and display it as you need to.
