user5896534
user5896534

Reputation: 113

In Python, how do you create a new function that will modify an existing dictionary?

For example, I've already created a function that will create a nested dictionary. However, I'm trying to create a new function that will modify an existing dictionary by changing certain values within it. Here is my shot at it

myclasses={}
def addcourse(myclasses,department,course_number,term,grade,units):
    myclasses[department]={}
    if course_number in myclasses[department]:
        old=myclasses[department][course_number]
        old.append(term)
        old.append(grade)
        old.append(units)
        myclasses[department][course_number]=list(set(old))
    else:
        myclasses[department][course_number]=[term,grade,units]
def modifycourse(myclasses,department,course_number=newvalue,grade=newvalue,units=newvalue):
    try:
        if newvalue is course_number:
            grade=newvalue
            units=newvalue
    except:
        print "error"

addcourse(myclasses,"Math","350","Spring 2016","A",3)
addcourse(myclasses,"Math","350","Spring 2017","A",3)
addcourse(myclasses,"Physics","401","Fall 2016","B",3)
modifycourse(myclasses,"Physics","401","A",3)
print myclasses

I'm supposed to have the function and its keyword parameters named as listed in my code. So where am I going wrong?

Here is my output

error
{'Physics': {'401': ['Fall 2016', 'B', 3]}, 'Math': {'350': ['Spring 2017', 'A', 3]}}

Upvotes: 0

Views: 71

Answers (1)

skrrgwasme
skrrgwasme

Reputation: 9633

Python functions use pass-by reference, so you can freely modify a passed-in dictionary. You don't have to do anything special:

>>> d = {'a':1, 'b':2} # create dictionary
>>> def mod(dict):     # create function to modify input dictionary
...     dict['b'] = 3  # change the input dictionary
...
>>> print(d)           # print dictionary before changes
{'a': 1, 'b': 2}
>>> mod(d)             # modify dictionary
>>> print(d)           # print modified dictionary
{'a': 1, 'b': 3}

Note that in my mod() function, I actually change the input argument. Your function isn't doing that. You need to have something in your modifycourse() function that actually indexes into the input dictionary and changes it:

myclasses[department] = # new value

Upvotes: 3

Related Questions