Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add values to existing dictionary key Python

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 time and then append that to a list of tuples, as we will be running this function multiple times. Then I am trying to put certain parts of the list of tuples to certain keynames.

I think it's better if I would show you would the output looks like:

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)]}

This is my code so far:

aDict = {}
tupleList = []
def insertIntoDataStruct(name,startTime,endTime,aDict):       
    timeTuple = tuple([startTime, endTime])  
    tupleList.append(timeTuple)
    aDict[name] = tupleList
    return aDict

I know that this will give me a dictionary with each key having ALL values, but I have no idea on how to make it so that each value that I add will be added on to the dictionary as seen in the output. I have tried a lot of random things, but I am still stuck on this. :(

like image 643
OmicronAlpha Avatar asked Sep 15 '13 21:09

OmicronAlpha


1 Answers

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")))
like image 52
Graeme Stuart Avatar answered Nov 01 '22 18:11

Graeme Stuart