基本上有 15 個(gè)問(wèn)題從Question 1到Question 15作為父詞典中的嵌套詞典Questions。但現(xiàn)在我想用這個(gè)列表更新這本詞典,其中也有 15 個(gè)問(wèn)題:new_list = ['Question 6', 'Question 7', 'Question 8', 'Question 9', 'Question 10', 'Question 11', 'Question 12', 'Question 13', 'Question 14', 'Question 15', 'Question 16', 'Question 17', 'Question 18', 'Question 19', 'Question 20']這只是Question n + 5人類(lèi)語(yǔ)言。但我一整天都在掙扎。我觀察到的奇怪行為是:方法1-for ind, val in enumerate(list(q_dict['Questions'].keys())):
q_dict['Questions'][new_list[ind]] = q_dict['Questions'].pop(val)結(jié)果是:{'Paper Name': 'Paper 8.jpg', 'Category': 1, 'Questions': {'Question 16': {'Question Type': 1, 'Question Point': [], 'Expected Answers': [], 'Student Answers': []}, 'Question 17': {'Question Type': 3, 'Question Point': [], 'Expected Answers': [], 'Student Answers': []}, 'Question 18': {'Question Type': 3, 'Question Point': [], 'Expected Answers': [], 'Student Answers': []}, 'Question 19': {'Question Type': 3, 'Question Point': [], 'Expected Answers': [], 'Student Answers': []}, 'Question 20': {'Question Type': 3, 'Question Point': [], 'Expected Answers': [], 'Student Answers': []}}}方法2-for ind, val in enumerate(list(q_dict['Questions'].keys())):
q_dict['Questions'][new_list[ind]] = q_dict['Questions'][val] del q_dict['Questions'][val]結(jié)果:{'Paper Name': 'Paper 8.jpg', 'Category': 1, 'Questions': {'Question 6': {'Question Type': 1, 'Question Point': [], 'Expected Answers': [], 'Student Answers': []}, 'Question 7': {'Question Type': 3, 'Question Point': [], 'Expected Answers': [], 'Student Answers': []}, 'Question 8': {'Question Type': 3, 'Question Point': [], 'Expected Answers': [], 'Student Answers': []}, 'Question 9': {'Question Type': 3, 'Question Point': [], 'Expected Answers': [], 'Student Answers': []}, 'Question 10': {'Question Type': 3, 'Question Point': [], 'Expected Answers': [], 'Student Answers': []}}}
2 回答

慕的地8271018
TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
從您正在迭代的列表中添加或刪除元素通常是一個(gè)壞主意,因?yàn)樾袨榭赡懿皇悄谕?。相反,完全替換問(wèn)題字典:
q_dict['Questions'] = { name: entry for name, entry in zip(new_list, q_dict['Questions'].values())}
請(qǐng)注意,在 Python 3.6 之前,您可能需要對(duì)值進(jìn)行排序,因?yàn)闊o(wú)法保證迭代順序。

一只名叫tom的貓
TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
我想分享另一種解決此問(wèn)題的方法,該方法不涉及額外的鍵列表(只需在每個(gè)問(wèn)題鍵上添加 5):
import re
def change_name(m_str):
a = re.match('\D+(\d+)', m_str)
return m_str.replace(str(a.groups()[0]), str(int(a.groups()[0])+5))
q_dict["Questions"] = {change_name(inner_key):inner_val for inner_key, inner_val in q_dict["Questions"].items()}
添加回答
舉報(bào)
0/150
提交
取消