追加时覆盖Dict

2024-07-05 14:12:32 发布

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

我有一个csv看起来像这样

0   0001eeaf4aed83f9    freeform    /m/0cmf2    1   0.022464    0.964178    0.070656    0.800164    0   0   0   0   0
1   000595fe6fee6369    freeform    /m/02wbm    1   0.000000    1.000000    0.000233    1.000000    0   0   1   0   0
2   000595fe6fee6369    freeform    /m/02xwb    1   0.141030    0.180277    0.676262    0.732455    0   0   0   0   0
3   000595fe6fee6369    freeform    /m/02xwb    1   0.213781    0.253028    0.298764    0.354956    1   0   0   0   0
4   000595fe6fee6369    freeform    /m/02xwb    1   0.232926    0.288447    0.488954    0.545146    1   0   0   0   0

正如您在第二列中看到的,第一个值只出现一次,但是第二个值出现了4次,我在这里尝试的是将第二列值设置为键,并将第6、7、8和9个元素作为值附加到字典中。如果键相同,则继续追加,不要覆盖以前的值。我现在拥有的是

image_dict={}
for index, item in enumerate(data.ImageID):
    image_dict[item] = []
    image_dict[item].append((data.XMax[index], data.XMin[index], data.YMax[index], data.YMin[index]))

这让我

{'0001eeaf4aed83f9': [(0.96417800000000009,
   0.022463999999999998,
   0.80016399999999999,
   0.070655999999999997)],
 '000595fe6fee6369': [(0.25302800000000003,
   0.213781,
   0.35495599999999999,
   0.29876399999999997)]}

正如您可以在元素的第二个键中看到的那样,值已被覆盖,如何避免这种情况

任何建议都会很有帮助,提前谢谢


Tags: csvinimage元素fordataindex字典
2条回答

签出^{}

from collections import defaultdict

image_dict = defaultdict(list)
for index, item in enumerate(data.ImageID):
    image_dict[item].append((data.XMax[index], data.XMin[index], data.YMax[index], data.YMin[index]))

如果不存在空列表,它将创建一个空列表并附加到该列表。参见文档中的example

每次迭代都会覆盖列表。相反,如果不创建新的键列表,您可以检查dict中是否存在该键

例如:

image_dict={}
for index, item in enumerate(data.ImageID):
    if item not in image_dict:
        image_dict[item] = []
    image_dict[item].append((data.XMax[index], data.XMin[index], data.YMax[index], data.YMin[index]))

相关问题 更多 >