首页 > 解决方案 > 将dict添加到for循环中的列表

问题描述

根据我的调试器和我的 25 行测试 csv,该patient_appts列表包含预期的 25 个字典。我似乎无法弄清楚该列表是如何None在局部变量、返回语句和主函数之间形成的。

我已经在几个地方读到了您需要制作副本而不是附加参考,据我所知,我已经这样做了,使用 patient_appts.append(entry.copy())

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

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

发生异常。TypeError,“NoneType”类型的对象没有 len()

调试器清楚地显示列表中的字典,然后再将其变为return

调试器图片

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()

标签: pythonpython-3.xlistdictionary

解决方案


您在函数中有一个随机return语句run_CSV,当您点击该函数时,您的函数什么也不返回 -None

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

它应该如下所示:

    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)
            break # formerly "return" was here

推荐阅读