Python:基于匹配将元素插入字典中的列表

3

我将尝试向一个列表中插入值,该列表首先通过识别匹配项而被打包到字典中。如果我有这样的字典:

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

我目前正在尝试逐行读取文件,并识别我的字典中是否存在该键。然后确定值是否匹配或存在于字典键返回的列表中。在这一点上,我想要将匹配值旁边的行中的一个值插入到列表中。
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'))

很不幸,似乎由于某种我无法确定的原因,它似乎卡在了数据循环中。只需将值附加到列表中即可正常工作,但这样做很混乱,而且有近3k个值,我不想手动操作。

非常感谢任何帮助,让我知道我哪里出错了。我觉得我做得相当低效,但我愿意学习。

1个回答

3
您正在迭代列表时修改它。
一种解决方法:
        #iterate over the list in the dictionary
        for item in Ndates[splitline[0]][:]:

这会在迭代之前复制列表。
但我建议重构代码:
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*

1
非常感谢。你的解决方案非常好,我真的很喜欢它将问题分解得如此清晰明了。我有一种感觉,就是在迭代列表时修改它是问题所在,但不确定应该在哪里进行修复。再次感谢你。 - ryfi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接