How to add values to existing dictionary key Python

后端 未结 2 1073
走了就别回头了
走了就别回头了 2021-02-03 10:43

I am trying to create a function that takes in four parameters: A keyname, start time, end time, and then a dictionary. I have to create a tuple out of the start time and end ti

2条回答
  •  广开言路
    2021-02-03 11:05

    Try this:

    def insertIntoDataStruct(name,startTime,endTime,aDict):
        if not name in aDict:
            aDict[name] = [(startTime,endTime)]
        else:
            aDict[name].append((startTime,endTime))
    

    Now define your dict:

    courses = {}
    

    and start adding the courses:

    insertIntoDataStruct("CS 2316", "1505", "1555", courses)
    insertIntoDataStruct("CS 2316", "1405", "1455", courses)
    insertIntoDataStruct("CS 2316", "1305", "1355", courses)
    insertIntoDataStruct("CS 4400", "1405", "1455", courses)
    insertIntoDataStruct("CS 4400", "1605", "1655", courses)
    

提交回复
热议问题