[英]Python: Unable to add a new key:value to a dictionary
我正在制作一本字典,用于存储针对不同学生的测验及其成绩。
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()
但是,当我尝试向我的字典添加新的key:value
,出现两个错误:
第一:
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})
TypeError: cannot convert dictionary update sequence element #0 to a sequence
第二:
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
。
test1.update({'charles',100})
正在使用一组而不是一组dict来更新该dict,它显然不能用于更新...而不是通过set传递它
test1.update({'charles':100})
只是为了展示
{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)
如果我了解您的需要,则需要添加新值而不更新,并且对于该操作,您需要更改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()
并得到回应:
one - {'john': 95, 'charles': 100, 'jeanie': 100, 'chris': 92, 'craig': 88}
two - {'john': 100, 'charles': 98, 'jeanie': 95, 'chris': 96, 'craig': 85}
three - {'john': 97, 'charles': 94, 'jeanie': 98, 'chris': 100, 'craig': 80}
您的问题是,update用键搜索一个字典以更新您的值,而不插入,但setdefault插入新对key:value且该语法不存在,并返回其存在的一个键的值。
对你来说很好
在这里查看答案:
更新:
#### 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)])
代替这个:
test3.update({'charles',94})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.