Python将字典作为值插入到具有相同键的新字典中

2024-09-30 01:19:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我的函数为我提供以下格式的词典-

{
  "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

我试图将diff_data[section]=data更改为-

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'

任何线索,我应该如何处理这个问题。这似乎是一个简单的问题,但我无法获得正确的格式作为所需的输出。输出中所有值的键都需要是“section”,这增加了获得正确输出的复杂性


Tags: anddataiflinediffupdatesectionstart

热门问题