猿问

使用列表更新嵌套字典时的奇怪行为

基本上有 15 个问题从Question 1Question 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': []}}}



郎朗坤
浏览 128回答 2
2回答

慕的地8271018

从您正在迭代的列表中添加或删除元素通常是一个坏主意,因为行为可能不是您所期望的。相反,完全替换问题字典:q_dict['Questions'] = {     name: entry for name, entry in zip(new_list, q_dict['Questions'].values())}请注意,在 Python 3.6 之前,您可能需要对值进行排序,因为无法保证迭代顺序。

一只名叫tom的猫

我想分享另一种解决此问题的方法,该方法不涉及额外的键列表(只需在每个问题键上添加 5):import redef 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()}
随时随地看视频慕课网APP

相关分类

Python
我要回答