🎉 سال نو، مهارت نو، مشاوره رایگان نقشه راه برنامه نویسی (آفر ویژه ثبت نام قبل از افزایش قیمت 🔥)
۰ ثانیه
۰ دقیقه
۰ ساعت
۱ احسان مرادیان
خطای:key error
محسن موحد حل شده توسط محسن موحد

با سلام 

کدم به خطا خورده و نمیدونم علتش چیه

def show_reports():
    for report in reports_collection.find():
        duration = report['end_time'] - report['start_time']
        print(f"{report['user']['username']}\t {report['project']['name']}\t {duration.seconds}")

 

و متن خطاش هم اینه:

  File "/home/aio-user/python/step/project/main.py", line 42, in show_reports
   duration = report['end_time'] - report['start_time']
              ~~~~~~^^^^^^^^^^^^
KeyError: 'end_time'
 

سلام،

کلید end_time در دیکشنری وجود ندارد.

میتونید در کدتون چک کنید کلیدهارو:

def show_reports():
    for report in reports_collection.find():
        if 'start_time' in report and 'end_time' in report:
            duration = report['end_time'] - report['start_time']
            print(f"{report['user']['username']}\t {report['project']['name']}\t {duration.seconds}")
        else:
            print("Report is missing start_time or end_time")
بهترین پاسخ
محسن موحد ۱۸ آذر ۱۴۰۲، ۰۷:۲۸