首页 > 解决方案 > 将 for 循环迭代的结果存储在字典中

问题描述

我是 Python 新手,并开始从一些教程中学习它。

我有一个 for 循环,它将输出存储在字典中。在代码的末尾,字典正在更新,仅存储最后一次 for 循环迭代的结果。这是 for 循环的基本功能,没问题。

我只想拥有从 for 循环迭代的不同字典中的所有值。

以下是我的代码

from collections import defaultdict
import glob
from PIL import Image
from collections import Counter

for file in glob.glob('C:/Users/TestCase/Downloads/test/*'): 

    by_color = defaultdict(int)
    im = Image.open(file)
    for pixel in im.getdata():
        by_color[pixel] += 1
    by_color

    # Update the value of each key in a dictionary to 1
    d = {x: 1 for x in by_color}
    # Print the updated dictionary

    check = dict(d)

    print(check) // Print the results from the for loop

 print(check) // Prints only the last iteration result of for loop

编辑:

从下面发布的答案中,我得到了一个包含所有键和值的字典列表。

实际输出:

[{(0, 255, 255): 1, (33, 44, 177): 1, (150, 0, 0): 1, (255, 0, 255): 1, (147, 253, 194): 1, (64, 0, 64): 1, {(0, 255, 255): 1, (33, 44, 177): 1, (150, 0, 0): 1, (96, 69, 143): 1, (255, 0, 255): 1}]

期望的输出:

[{(0, 255, 255): 2, (33, 44, 177): 2, (150, 0, 0): 2, (96, 69, 143): 1, (255, 0, 255): 2, (147, 253, 194): 1, (64, 0, 64): 1}]

标签: pythonpython-3.xdictionaryfor-loop

解决方案


您可以创建一个列表来存储您的字典并在每次迭代结束时添加字典。它看起来像这样:

from collections import defaultdict
import glob
from PIL import Image
from collections import Counter

my_dicts = []

for file in glob.glob('C:/Users/TestCase/Downloads/test/*'): 

    by_color = defaultdict(int)
    im = Image.open(file)
    for pixel in im.getdata():
        by_color[pixel] += 1
    by_color

    # Update the value of each key in a dictionary to 1
    d = {x: 1 for x in by_color}
    # Print the updated dictionary

    check = dict(d)

    print(check) # Print the results from the for loop

    my_dicts.append(check)

print(my_dicts) # Prints the dictionaries stored in a list

编辑:要回答您的其他问题,您可以使用计数器来实现您想要做的事情:

from collections import defaultdictfrom
import glob
from PIL import Image
from collections import Counter

my_dicts = []

for file in glob.glob('C:/Users/TestCase/Downloads/test/*'): 

    by_color = defaultdict(int)
    im = Image.open(file)
    for pixel in im.getdata():
        by_color[pixel] += 1
    by_color

    # Update the value of each key in a dictionary to 1
    d = {x: 1 for x in by_color}
    # Print the updated dictionary

    check = dict(d)

    print(check) # Print the results from the for loop

    my_dicts.append(check)

my_counters = [Counter(d) for d in my_dicts]

res = Counter()
for c in my_counters:
    res += c
output = dict(res)

推荐阅读