簡體   English   中英

Python - 如何將現有字典添加到一組新鍵中

[英]Python - How do i add an existing dictionary to a set of new keys

我的函數給了我以下格式的字典-

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

任何線索,我應該如何處理這個。 這似乎是一個簡單的問題,但我無法正確地將格式設置為所需的輸出。 如何編寫循環以將現有字典作為值插入到新的一組鍵中 - “section1, section2 ... ...”

我會復制字典,將原始鍵作為引用name值,並創建一個新鍵來引用新的字典。

diff_data = {}
i = 1

for key, d in x.items():
    new_dict = d.copy()
    new_dict['name'] = key
    new_key = "section_{}".format(str(i))
    diff_data[new_key] = new_dict
    i += 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM