Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: inserting into a list within a dictionary based on matching

I'm currently trying to insert values into a list, that is packed into a dictionary by first identifying a match. If I have a dictionary as such:

{'12633': ['11-Mar-11', '26-Apr-11'], '11359': [], '11458': ['6-Aug-10'], '16335': ['29-May-13'], '11101': []}

What I'm currently trying to do is read over a file by line and identify if the key exists in my dictionary. Then identify if the value matches or exists in the list returned by the dictionary key. At this point, I want to insert a value from the line next to the matched value in the list.

with open('Pfa.csv', 'r') as f:
    for line in f:
        #split the line up into individual element - it's a csv file
        line = line.strip('/n')
        splitline = line.split(',')
        #check if the value in the file exists as a key in the dictionary
        if splitline[0] in Ndates:
            #iterate over the list in the dictionary
            for item in Ndates[splitline[0]]:
                #check if the item within the dictionary list is within this line in the file
                if item == splitline[1]:
                    #insert a vale from the file next to the value in the list within the dictionary
                    Ndates[splitline[0]].insert(Ndates[splitline[0]].index(item), splitline[4].strip('\n'))

Unfortunately, it seems to be stuck looping over the data for some reason I cannot identify. Just appending the value to the list works, however it is messy and with almost 3k values, I don't want to do it by hand.

Any help is greatly appreciated to let me know where I'm going wrong. I feel like I'm doing this pretty inefficiently, but I'm willing to learn.

like image 900
ryfi Avatar asked Apr 23 '26 10:04

ryfi


1 Answers

You are modifying the list as you are iterating over it.

One fix:

        #iterate over the list in the dictionary
        for item in Ndates[splitline[0]][:]:

This copies the list before iterating.

But I would suggest refactoring:

import csv

with open('Pfa.csv') as f: #'r' is default
    for row in csv.reader(f):
        key = row[0]
        try:
            values = Ndates[key]
            i = values.index(row[1])
        except (KeyError, ValueError):
            pass
        else:
            values.insert(i, row[4]) #this will insert *before* the match; use i + 1 insert *after*
like image 94
Paul Draper Avatar answered Apr 26 '26 01:04

Paul Draper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!