簡體   English   中英

在Python中,如何創建新函數來修改現有字典?

[英]In Python, how do you create a new function that will modify an existing 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]}}

Python函數使用傳遞引用,因此您可以自由地修改傳遞字典。 您不必做任何特別的事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM