在Python中,如何创建一个修改现有字典的新函数?

时间:2016-11-08 01:20:18

标签: python python-2.7 function dictionary

例如,我已经创建了一个将创建嵌套字典的函数。但是,我尝试创建一个新函数,通过更改其中的某些值来修改现有字典。这是我的镜头

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

我应该将我的代码中列出的函数及其关键字参数命名为。那么我哪里出错?

这是我的输出

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

1 个答案:

答案 0 :(得分:3)

Python函数使用pass-by引用,因此您可以自由修改传入的字典。你不需要做任何特别的事情:

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

请注意,在我的mod()函数中,我实际上更改了输入参数。你的功能不是那样做的。您需要在modifycourse()函数中有一些实际索引到输入字典中并对其进行更改的内容:

myclasses[department] = # new value