Schütze
Schütze

Reputation: 1084

Accessing List of Dictionary Items

I have the following code to create a list of dictionaries of images:

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)

which bascially reads the images under a folder and puts them into list of dictionaries.

I'd like to read then each of their dictionary values and keys into variables in a loop properly. So I am trying the following:

for dict in planet_templates:
    for key in dict:
        print(dict[key])

However this does not give me what I want. Instead, throws the whole list without any name, width or height tagged:

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

whereas I'd like to have:

name: templates/neptune.png
height: 148
width: 107

and even assign them to variables, if possible. Such as:

width, height, name = templates[i].shape[::-1]

Of course shape[::-1] here won't work because dictionary has no such attribute, but you get the point, something equivalent.

How can I achieve this? Thanks in advance.

Upvotes: 1

Views: 51

Answers (1)

Rakesh
Rakesh

Reputation: 82765

Use

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))

Output:

width: 107
name: templates/neptune.png
height: 148

Upvotes: 3

Related Questions