【发布时间】:2019-12-31 10:37:15
【问题描述】:
我是 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}]
【问题讨论】:
-
你已经更新了同一个键的值
标签: python python-3.x dictionary for-loop