需要将约会添加到空字典中

2024-09-30 04:26:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用python制作一个预约日历应用程序,我正在努力完成第一部分。你知道吗

我有一本叫做约会的空字典,我正在尝试添加约会。它在工作,但由于某些原因,它没有累积任命:

appointments = {}
while (True):
(... I had a choice variable here that would ask the user to either make an appointment, cancel, or view list of appointments. but for right now, i am only focusing on making appointments.)

    elif choice == 1: #Making an appointment
        apptDate = input('Enter date (mm/dd/yy)\n')
        apptTime = input('Enter time (hh:mm)\n')
        apptDesc = input('Enter a brief description of the appointment\n')

        #Checking to see if key in dictionary
        if apptDate not in appointments:
           newAppt = apptTime + '\t' + apptDesc
           appointments[apptDate] = newAppt
        else:
           appointments[apptDate] = newAppt
  1. 我必须使用apptDate作为键将apptTime+'\t'+apptDesc放入约会字典中。我认为我做得对。

  2. 检查apptDate是否已经在约会字典中,因为它会影响它应该添加新约会的方式。

任何帮助都很好,谢谢


Tags: ofthetoaninput字典appointment约会
2条回答
appointments = [] 

是一个列表

appointments = {}

这是一本字典

检查一个键是否在字典中使用

if key in dictionary: 

(其中键为apptDate)

出于您的目的,请使用默认dict(从集合导入)。这允许您初始化字典,以便在某个键不在其中时为该键指定一个特定的值。在您的情况下,您可能希望考虑每个日期都有一个约会列表(因此,如果没有约会,则默认的dict用空列表初始化:

from collections import defaultdict
def default():
    return []

appointments = defaultdict(default)

然后,无论何时,只要您想将约会添加到密钥,就可以这样做

appointments['date'].append("Info")

这是相当干净的,避免了检查语句

编辑:如果你坚持按自己的方式做,最后一段可以是:

if apptDate not in appointments:
       newAppt = apptTime + '\t' + apptDesc
       appointments[apptDate] = [newAppt]
else:
       newAppt = apptTime + '\t' + apptDesc
       appointments[apptDate].append(newAppt)

相关问题 更多 >

    热门问题