基本上有 15 個問題從Question 1到Question 15作為父詞典中的嵌套詞典Questions。但現在我想用這個列表更新這本詞典,其中也有 15 個問題: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人類語言。但我一整天都在掙扎。我觀察到的奇怪行為是:方法1-for ind, val in enumerate(list(q_dict['Questions'].keys())):
q_dict['Questions'][new_list[ind]] = q_dict['Questions'].pop(val)結果是:{'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]結果:{'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貢獻1796條經驗 獲得超4個贊
從您正在迭代的列表中添加或刪除元素通常是一個壞主意,因為行為可能不是您所期望的。相反,完全替換問題字典:
q_dict['Questions'] = { name: entry for name, entry in zip(new_list, q_dict['Questions'].values())}
請注意,在 Python 3.6 之前,您可能需要對值進行排序,因為無法保證迭代順序。

一只名叫tom的貓
TA貢獻1906條經驗 獲得超3個贊
我想分享另一種解決此問題的方法,該方法不涉及額外的鍵列表(只需在每個問題鍵上添加 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()}
添加回答
舉報
0/150
提交
取消