0

In Perl, I can iterate over a csv file and update an array pointed to by a key of a hash automagically. Suppose I had a file like this:

foo,1
foo,2
bar,3
baz,2
baz,1
baz,5

Then I can loop like this (pseudo-code):

for ($key,$val in csv file) {
  push($hash{$key}, $val)
}

Such that I end up with a structure like this:

$hash = {
foo : [1,2]
bar : [3]
baz : [2, 1, 5]
}

What is the Pythonic way to accomplish the same?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Lucky
  • 627
  • 5
  • 15
  • Are there any gotchas with adding an element to the dict that is NOT a list? e.g., "dict['elem'] = 33143" ? – Lucky May 14 '21 at 04:55

1 Answers1

1

Try this:

my_dict = dict()
with open("data.csv") as f:
    for key, val in enumerate(f):
        if key in my_dict:
            my_dict[key].append(val)
         else:
             my_dict[key] = [val]   
        
print(my_dict)
Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22