python – 迭代字典,添加键和值
发布时间:2020-12-20 12:39:43 所属栏目:Python 来源:网络整理
导读:我想迭代一本字典,每次修改字典而不是当前正在发生的字典,而是用新的字符重置旧值. 我目前的代码是: while True: grades = { raw_input('Please enter the module ID: '):raw_input('Please enter the grade for the module: ') } 但是,这不会修改列表,而是
我想迭代一本字典,每次修改字典而不是当前正在发生的字典,而是用新的字符重置旧值.
我目前的代码是: while True: grades = { raw_input('Please enter the module ID: '):raw_input('Please enter the grade for the module: ') } 但是,这不会修改列表,而是删除以前的值.我该如何修改字典呢? (另外,当我运行它时,它希望我在键之前输入值,为什么会发生这种情况?) 解决方法
在您的示例中,每次使用新的键值对刷新成绩(字典).
>>> grades = { 'k':'x'} >>> grades {'k': 'x'} >>> grades = { 'newinput':'newval'} >>> grades {'newinput': 'newval'} >>> 你应该做的是更新同一个dict的键值对: >>> grades = {} >>> grades['k'] = 'x' >>> grades['newinput'] = 'newval' >>> grades {'k': 'x','newinput': 'newval'} >>> 试试这个: >>> grades = {} >>> while True: ... k = raw_input('Please enter the module ID: ') ... val = raw_input('Please enter the grade for the module: ') ... grades[k] = val ... Please enter the module ID: x Please enter the grade for the module: 222 Please enter the module ID: y Please enter the grade for the module: 234 Please enter the module ID: z Please enter the grade for the module: 456 Please enter the module ID: Please enter the grade for the module: Please enter the module ID: Traceback (most recent call last): File "<stdin>",line 2,in <module> KeyboardInterrupt >>> >>> grades {'y': '234','x': '222','z': '456','': ''} >>> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |