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)


索,我应该如何处理这个问题。这似乎是一个简单的问题,但我无法将格式正确地作为所需的输出。如何编写循环以将现有字典作为值插入到新的键集 - “section1,section2 ...”


交互式爱情
浏览 112回答 1
1回答

忽然笑

我会复制字典,将原始键作为值与 reference name,并创建一个新键来引用新字典。diff_data = {}i = 1for 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python