1

I'm struggling with Python, specifically adding/updating keys and values in a dictionary.

This is my code so far (I know it's probably far from perfect, this is my first time working with Python, apart from the much easier first part of PSET6):

from sys import argv, exit
import csv


if len(argv) != 3:
    print("Usage: python dna.py data.csv sequence.txt")
    exit(0)

with open(argv[2]) as dnafile:
    dna = dnafile.read()

names = []
people = {}
nSTRs = []

with open(argv[1]) as csvfile:
    dreader = csv.DictReader(csvfile)
    STRs = dreader.fieldnames[1:]

    peoplereader = csv.reader(csvfile)
    for row in peoplereader:
        names.append(row[0])
        nSTRs.append(row[1:])

    print(nSTRs)

    dictSTRs = {}
    for STR in STRs:
        dictSTRs.update({STR: ''})


for name in names:
    people.update({name: dictSTRs})

print(people)

n = 0
for name in people:
    s = 0
    for STR in STRs:
        people[name].update({STR: nSTRs[n][s]})
        print(people)
        s += 1
    n += 1


print(people)

I want to get a dictionary people with the names as keys and another dictionary dictSTRs as values, where dictSTRs has the STRs as keys and the numbers of occurrences for each person as values. I think I'm almost there, but the last (2 nested) loop(s) in the code seems to change people for every name every time it runs, i.e. in the end I'm left with all names having the STR values of the last person.

Is there a way to fix this? I've tried using people.update({name: {STR: nSTRs[n][s]}}) instead, but that didn't work either as it just completely replaced all the STRs, leaving only the last one behind for each.

You must log in to answer this question.

Browse other questions tagged .