Python-将字典作为值插入到具有相同键的新字典中
我的函数为我提供以下格式的词典-Python-将字典作为值插入到具有相同键的新字典中,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我的函数为我提供以下格式的词典- { "key1": { "deleted": [], "inserted": [] }, "key2": { "deleted": [ { "end": 5, "line": "", "start": 5 } 但是,我希望得到如下输出- { "section1": {
{
"key1": {
"deleted": [],
"inserted": []
},
"key2": {
"deleted": [
{
"end": 5,
"line": "",
"start": 5
}
但是,我希望得到如下输出-
{ "section1":
{
"name":"key1",
"deleted":[],
"inserted":[],
}
},
{ "section2":
{
"name":"key2",
"deleted":[],
"inserted":[],
}
},
{ "section3":
{
"name":"key3",
"deleted":[],
"inserted":[],
}
},
我所写的函数是-
diff_data = {}
with open('2018temp.json', 'w') as f1t, open('2019temp.json', 'w') as f2t:
json.dump(f1_dict, f1t)
json.dump(f2_dict, f2t)
for section in settings['includes']:
f1_text = f1_dict.get(section, [])
f2_text = f2_dict.get(section, [])
diffile = []
diff = difflib.Differ()
with open('diffile.txt', 'a') as f:
for line in diff.compare(f1_text, f2_text):
f.write(line + ('\n' if not line.endswith('\n') else ''))
if line.startswith(("-", "+", "?")):
diffile.append(line)
data = {'deleted': [], 'inserted': []}
for i, line in enumerate(diffile[:-1]):
if line.startswith('-'):
if diffile[i+1].startswith('?'): # Deletion and modification
updated_line = diffile[i+2]
update_start = re.search('[-+^]', diffile[i+1]).start()
update_end = re.search('[-+^][^-+^]*$', diffile[i+1]).start()
data['deleted'].append({'line': diffile[i+2][2:], 'start': update_start, 'end': update_end})
elif diffile[i+1].startswith('+') and i+2 < len(diffile) and diffile[i+2].startswith('?'):
pass # Addition and modification, do nothing
else:
data['deleted'].append(line[2:]) # Pure deletion
elif line.startswith('+'):
if diffile[i+1].startswith('?'): # Addition and modification
update_start = re.search('[-+^]', diffile[i+1]).start()
update_end = re.search('[-+^][^-+^]*$', diffile[i+1]).start()
data['inserted'].append({'line': line[2:], 'start': update_start, 'end': update_end})
else:
data['inserted'].append(line[2:]) # Pure addition
diff_data[section] = data
任何线索,我应该如何处理这个问题。这似乎是一个简单的问题,但我无法获得正确的格式作为所需的输出。输出中所有值的键都必须是“section”,这增加了获得正确输出的复杂性。乍一看,您是否打算将“section”作为键使用两次(这在设计上是不可能的)?如果是这样,那么您可能只需要一个对象列表,这是一个非常简单的更改。还是应该像“第一节”,“第二节”?您在示例中投入了大量精力,因此您最好完成此工作,以便我可以实际运行它来重新创建您的问题。一个字典中不能有相同的键,这不是字典的含义。让我们再看看。正如@EkremDİNİEL所提到的,使用相同的键会导致冲突,这意味着最新的“部分”将始终覆盖词典中的前一部分。如果要存储多个“节”,则必须遵循JSON约定(“节对象列表”),即:
{“节”:[{“名称”:“key1”,“deleted”:[],…},…},…]}
@KennyOstrom:我的意思是使用“节”两次,但是,我认为根据注释中的解释,我必须使用-'section1,section2。我会相应地更新我的帖子。你应该使用你已有的“key1”和“key2”,或者将其转换为数组。然而,您可以添加“name”,即使它是多余的(我不会)。真正的问题是你为什么想要错误的输出?我们也许能在那里帮忙。
diff_data.setdefault('section',[]).append(data)
AttributeError: 'dict' object has no attribute 'append'
diff_data['section'].append(data)
AttributeError: 'dict' object has no attribute 'append'
diff_data.append({'section': [data]})
AttributeError: 'dict' object has no attribute 'append'