返回字典中包含多个键的最大值

2024-07-08 10:17:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个宽度和高度的图像字典,我想根据它们的宽度对它们进行排序,或者只是在字典值中找到最大宽度。 谢谢你的帮助。你知道吗

代码如下:

from PIL import Image 

folder_images = "data/train/melanoma"
size_images = dict()

for dirpath, _, filenames in os.walk(folder_images):
    for path_image in filenames:
        image = os.path.abspath(os.path.join(dirpath, path_image))
        with Image.open(image) as img:
            width, heigth = img.size
            size_images[path_image] = {'width': width, 'heigth': heigth}

for k, v in size_images.items():
    print (k, '-->', v)

输出:

ISIC_0011130.jpg --> {'width': 1024, 'heigth': 768}
ISIC_0013581.jpg --> {'width': 4288, 'heigth': 2848}
ISIC_0013832.jpg --> {'width': 3008, 'heigth': 2000}
ISIC_0014127.jpg --> {'width': 4288, 'heigth': 2848}
ISIC_0013861.jpg --> {'width': 4288, 'heigth': 2848}
ISIC_0000169.jpg --> {'width': 722, 'heigth': 542}
ISIC_0001140.jpg --> {'width': 1936, 'heigth': 1936}

Tags: pathinimageforsize字典宽度os
3条回答

要按高度升序打印图像:

for k, v in sorted(size_images.items(), lambda kv: kv[1]['height']):
    print (k, ' >', v)

如果要创建具有所需顺序的新dict,可以根据对原始dict项的排序结果创建^{}^{}按插入的顺序存储其项(而内置dict没有内部顺序)。你知道吗

from collections import OrderedDict

newDict = OrderedDict(sorted(oldDict.items(), key=lambda x: x[1]['width']))
largest = list(newDict.items())[-1]
# {'ISIC_0013861.jpg', {'width': 4288, 'heigth': 2848})

最大宽度

max与生成器表达式一起使用:

max_width = max(v['width'] for v in size_images.values()}

按宽度排序

对自定义键使用sorted

sorted_list = sorted(sizes_images.items(), key=lambda x: x[1]['width'])

注意,这将输出一个元组列表,首先按最小宽度排序。添加reverse=True以最大的开始。你知道吗

相关问题 更多 >

    热门问题