Search code examples
python-3.xlistdictionaryfor-loopcsvreader

How to append and item to the last appended item in a list with a for loop


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

Solution

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