我正在编一本字典,用来储存不同学生的考试成绩。在
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
。在
是用集合更新dict而不是dict,它显然不能用它来更新。。。而不是集合传递指令
^{pr2}$只是为了证明
请参阅此处的答案:
Add new keys to a dictionary?
要更新:
而不是这样:
^{pr2}$如果我理解您的需要,您需要添加新值而不是更新,对于该操作,您需要更改setdefault方法的更新。我在Aptana Studio上测试了以下代码:
然后得到回应:
^{pr2}$你的问题是update用键搜索一个字典来更新你的值,而不是insert而是setdefault insert new pair键:值该语法case not exists,并返回她存在的一个键case的值。在
干得好
相关问题 更多 >
编程相关推荐