在for循环中将dict添加到列表中

时间:2018-06-11 18:55:12

标签: python python-3.x list dictionary

根据我的调试器和我的25行测试csv,patient_appts列表包含25个预期的dicts。我似乎无法弄清楚该列表如何在局部变量,return语句和main函数之间变为None

我已经在you need to make a copy的几个地方读过,而不是附加一个引用,据我所知,我使用patient_appts.append(entry.copy())

很抱歉,如果代码是一种火车残骸,我对此很新,并试图自动完成一些工作 - 例如,我很确定我不应该为我的数据手动创建json格式,但那是超出了这个问题的范围。

我尝试在全局范围内实例化列表,而不是在函数内,全局并在函数内声明全局,在with ed as ed_file:之后实例化列表;它们似乎都产生了相同的结果(print(len(appointments))):

  

发生了异常。 TypeError,类型为'NoneType'的对象没有   LEN()

调试器在进入return之前清楚地显示列表中的序列:

debugger picture

import csv
from datetime import datetime, timedelta
from validate_email import validate_email
from fieldMap import fieldMap

record_count = 0
valid_email_count = 0



def run_CSV(ed):
    with ed as ed_file:
        global record_count
        global valid_email_count
        patient_appts = []
        header_row = True
        ed_reader = csv.reader(ed_file, delimiter=',', quotechar='"')

        for row in ed_reader:
            if not row[0] and not row[1]:
                print('\n%i records written to csv' % record_count
                      + '\n%i valid emails found' % valid_email_count)
                return
            elif header_row:
                headers = list(row)
                i_fname = headers.index(fieldMap['FirstName'])
                i_mname = headers.index(fieldMap['MiddleName'])
                i_lname = headers.index(fieldMap['LastName'])
                i_email = headers.index(fieldMap['Email'])
                i_start = headers.index(fieldMap['StartTime'])
                i_end = headers.index(fieldMap['EndTime'])
                i_location = headers.index(fieldMap['Location'])
                i_type = headers.index(fieldMap['Type'])
                i_appt_id = headers.index(fieldMap['ApptID'])
                header_row = False
            else:
                duration = getDuration(row[i_start], row[i_end])
                start_time = row[i_start]
                end_time = row[i_end]
                valid_email = validate_email(row[i_email])

                if valid_email:
                    valid_email_count += 1
                record_count += 1

                entry = {
                    'ApptID': row[i_appt_id],
                    'Data': {
                        'Patient': {
                            'FirstName': row[i_fname],
                            'MiddleName': row[i_mname],
                            'LastName': row[i_lname],
                            'Email': row[i_email],
                            'Valid Email': valid_email,
                            'Appointment': {
                                'Type': row[i_type],
                                'Location': row[i_location],
                                'StartTime': start_time,
                                'EndTime': end_time,
                                'Duration': duration
                            }
                        }
                    }
                }
                patient_appts.append(entry.copy())
        return patient_appts

def getDuration(start_time, end_time):
    fmt = '%I:%M %p'
    tdelta = datetime.strptime(
        end_time, fmt) - datetime.strptime(start_time, fmt)
    duration = str(tdelta).split(':')[1]
    return duration


def main():
    appointments = run_CSV(open(input('Enter full CSV Path:\n'), newline='\n'))
    print(len(appointments))

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:3)

VM: IO Surface函数中有一个随机的return语句,当你点击它时,你的函数什么都没有返回 - run_CSV

当您的None功能尝试main len时,您将收到该错误。由于这是循环的一部分,我猜你打算使用None而不是break

它应该是这样的:

return