How to add values to existing dictionary key Python

后端 未结 2 1068
走了就别回头了
走了就别回头了 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)
    
    0 讨论(0)
  • 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")))
    
    0 讨论(0)
提交回复
热议问题