2014-01-22 1 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

관련 문제