Joh*_*ohn 1 python dictionary for-loop python-3.x
我是 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
Run Code Online (Sandbox Code Playgroud)
编辑:
从下面发布的答案中,我得到了一个字典列表,其中附加了所有键和值。
实际输出:
[{(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}]
Run Code Online (Sandbox Code Playgroud)
期望的输出:
[{(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}]
Run Code Online (Sandbox Code Playgroud)
您可以创建一个列表来存储字典,并在每次迭代结束时添加字典。它看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
编辑:要回答您的其他问题,您可以使用计数器来实现您想要做的事情:
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)
Run Code Online (Sandbox Code Playgroud)