1

I have a for loop that goes over each row in a CSV and I create a dictionary that has a list in it, but the list gets overridden because the dictionary key is repeated several times. How do I sum up or append to the list in the second(1) position the next value for the same key the next loop iteration?

Because with append the value gets overridden if an existing key is found again so the values of the key gets overridden over and over.

with open('RawPolicy.csv', newline='') as rulemaker:
    rmatcher = csv.reader(rulemaker, delimiter=" ")

    for i in rmatcher:
        dic[i[2]]=[i[0]],[i[1]]

The fields in the CSV are:

Sgrupo3 CSGrupo3 LLLLLLLL
Sgrupo4 CSGrupo4 LLLLLLLL

The output should be something like this:

{'LLLLLLLL': (['Sgrupo3', 'Sgrupo4'], ['CSGrupo3', 'CSGrupo4'])}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Heijs7
  • 27
  • 6

1 Answers1

1

You can use dict.setdefault to initialize each new key with a tuple of 2 sub-lists, and then iterate through both the sub-lists and the values in the current record by zipping them to append to each list with the corresponding value:

for *values, key in rmatcher:
    for lst, value in zip(dic.setdefault(key, ([], [])), values):
        lst.append(value)

Demo: https://repl.it/@blhsing/GratefulMountainousProperty

If your values and keys aren't necessarily in the first three columns, you can specify indices directly instead. The following code assumes the key at index 6 and values at indices 0 and 1:

for row in rmatcher:
    for lst, value in zip(dic.setdefault(row[6], ([], [])), row[:2]):
        lst.append(value)
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • That works pretty good with the example above but i made it so that i could be more clear to understand for the forum, but actually there are like 3 more colums for a total of 5 where i need to do the same operation, didnt know about that function so i dont know how to use with more than two colums. – Heijs7 Apr 16 '20 at 19:32
  • 1
    That did the job, thank you very much for the help. – Heijs7 Apr 16 '20 at 20:17