2014-01-22 43 views
3

我正在尝试将值插入到列表中,该列表通过首先标识匹配来打包到字典中。如果我有一本字典这样:Python:根据匹配插入到字典中的列表中

{'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的值,我不想亲自去做。

任何帮助非常感谢,让我知道我要去哪里错了。我觉得我这样做效率很低,但我愿意学习。

回答

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

相关问题