代码之家  ›  专栏  ›  技术社区  ›  Schütze

访问字典项列表

  •  1
  • Schütze  · 技术社区  · 7 年前

    我有以下代码来创建图像词典列表:

    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] 这里不起作用,因为dictionary没有这样的属性,但是你得到了要点,一些等价的东西。

    我怎样才能做到这一点?提前谢谢。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Rakesh    7 年前

    使用

    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