Python:无法添加新的键:值到字典

2024-06-01 09:07:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编一本字典,用来储存不同学生的考试成绩。在

def tests():
    test1 = {'craig':88, 'jeanie':100}
    test2 = {'craig':85, 'jeanie':95}
    test3 = {'craig':80, 'jeanie':98}
    return test1,test2,test3
def actions(test1,test2,test3):
    test1.update({'john':95})
    test1.update({'chris':92})
    test1.update({'charles',100})
    test2.update({'john':100})
    test2.update({'chris':96})
    test2.update({'charles',98})
    test3.update({'john':97})
    test3.update({'chris':100})
    test3.update({'charles',94})
    return test1,test2,test3
def main():
    one,two,three = tests()
    one,two,three = actions(one,two,three)
    print (test1,test2,test3)
main()

但是,当我试图在我的dicts中添加一个新的key:value时,会出现两个错误:

第一个:

^{pr2}$

第二:

Traceback (most recent call last):
  File "C:\file.py", line 26, in <module>
    main()
  File "C:\file.py", line 24, in main
    one,two,three = actions(one,two,three)
  File "C:\file.py", line 14, in actions
    test1.update({'charles',100})
ValueError: dictionary update sequence element #0 has length 7; 2 is required

如果我反复运行它,有时会出现第一个错误,有时会出现另一个错误。在

我不想要任何导入,如collections。在


Tags: actionsmaindefupdatejohnonechristhree
3条回答
test1.update({'charles',100})

是用集合更新dict而不是dict,它显然不能用它来更新。。。而不是集合传递指令

^{pr2}$

只是为了证明

{1,2,3,4,4,5,6}   # a set that will contain 1,2,3,4,5,6
{1:2,3:4,4:5}   # a dict with 3 elements dict(1=2,3=4,4=5)

请参阅此处的答案:

Add new keys to a dictionary?

要更新:

#### Inserting/Updating value ####
data['a']=1  # updates if 'a' exists, else adds 'a'
# OR #
data.update({'a':1})
# OR #
data.update(dict(a=1))
# OR #
data.update(a=1)
# OR #
data.update([(a,1)])

而不是这样:

^{pr2}$

如果我理解您的需要,您需要添加新值而不是更新,对于该操作,您需要更改setdefault方法的更新。我在Aptana Studio上测试了以下代码:

def tests():
    test1 = {'craig':88, 'jeanie':100}
    test2 = {'craig':85, 'jeanie':95}
    test3 = {'craig':80, 'jeanie':98}
    return test1,test2,test3
def actions(test1,test2,test3):
    test1.setdefault('john',95)
    test1.setdefault('chris',92)
    test1.setdefault('charles',100)
    test2.setdefault('john',100)
    test2.setdefault('chris',96)
    test2.setdefault('charles',98)
    test3.setdefault('john',97)
    test3.setdefault('chris',100)
    test3.setdefault('charles',94)
    return test1,test2,test3
def main():
    one,two,three = tests()
    one,two,three = actions(one,two,three)
    print(one,two,three)
main()

然后得到回应:

^{pr2}$

你的问题是update用键搜索一个字典来更新你的值,而不是insert而是setdefault insert new pair键:值该语法case not exists,并返回她存在的一个键case的值。在

干得好

相关问题 更多 >