Ryan
Ryan

Reputation: 10109

Overwriting Dict when appending

I have a csv which looks like this

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

As you can see in the second column the first value appears only once,but the second value appears 4 times ,What im trying to do here is set the second column values as keys and append the 6th, 7th, 8th and 9th elements as values to the dictionary. If the key is the same then keep appending and don't overwrite the previous values. What i have right now is

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]))

This gives me

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

As you can in the second key of the elements the values have been overwritten,How do i avoid this?

Any suggestions would be really helpful,Thanks in advance

Upvotes: 0

Views: 40

Answers (2)

Ben
Ben

Reputation: 6348

Check out collections.defaultdict:

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]))

It creates an empty list if none exists and appends to it. See the example in the docs.

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

You are overwriting the list with each iteration. Instead you can check to see if the key exist in the dict if not create a new key-list

Ex:

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]))

Upvotes: 2

Related Questions