[英]Accessing List of Dictionary Items
我有以下代碼來創建圖像詞典列表:
planet_templates = []
for file in glob.glob("templates/*.png"):
image = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
width, height = image.shape
imdict = {
'name': file,
'height': height,
'width': width,
}
planet_templates.append(imdict)
它基本上讀取文件夾下的圖像並將它們放入字典列表中。
我想將它們的每個字典值和鍵都正確地讀入循環中的變量。 所以我嘗試以下方法:
for dict in planet_templates:
for key in dict:
print(dict[key])
然而,這並沒有給我我想要的東西。 而是拋出整個列表,沒有標記任何名稱,寬度或高度:
222
templates/jupiter.png
294
713
templates/sun.png
137
161
templates/uranus.png
139
44
templates/mercury.png
44
50
templates/mars.png
50
200
templates/saturn.png
217
49
templates/venus.png
43
58
templates/earth.png
55
107
templates/neptune.png
148
而我想要:
name: templates/neptune.png
height: 148
width: 107
如果可能的話,甚至將它們分配給變量。 如:
width, height, name = templates[i].shape[::-1]
當然shape[::-1]
在這里不起作用,因為字典沒有這樣的屬性,但是你得到的點是等價的。
我怎樣才能做到這一點? 提前致謝。
采用
planet_templates = [{"name": "templates/neptune.png", "width": 107, "height": 148}]
for d in planet_templates:
for key, value in d.items():
print("{0}: {1}".format(key, value))
輸出:
width: 107
name: templates/neptune.png
height: 148
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.