How to add values to existing dictionary key Python

后端 未结 2 1069
走了就别回头了
走了就别回头了 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:09

    You might want to use a defaultdict instead.

    from collections import defaultdict
    
    def insertIntoDataStruct(name,startTime,endTime,aDict):
        aDict[name].append((int(startTime), int(endTime)))
        return aDict
    
    courses = defaultdict(list)
    courses = insertIntoDataStruct("CS 2316", "1505", "1555", courses)
    courses = insertIntoDataStruct("CS 2316", "1405", "1455", courses)
    courses = insertIntoDataStruct("CS 2316", "1305", "1355", courses)
    courses = insertIntoDataStruct("CS 4400", "1405", "1455", courses)
    courses = insertIntoDataStruct("CS 4400", "1605", "1655", courses)
    
    
    print courses == {'CS 2316': [(1505, 1555), (1405, 1455), (1305, 1355)], 'CS 4400': [(1405, 1455), (1605, 1655)]}
    print courses
    

    Perhaps you don't even need a function.

    from collections import defaultdict
    courses = defaultdict(list)
    courses["CS 2316"].append((int("1505"), int("1555")))
    courses["CS 2316"].append((int("1405"), int("1455")))
    courses["CS 2316"].append((int("1305"), int("1355")))
    courses["CS 4400"].append((int("1405"), int("1455")))
    courses["CS 4400"].append((int("1605"), int("1655")))
    

提交回复
热议问题