为了账号安全,请及时绑定邮箱和手机立即绑定

Python - 如何将现有字典添加到一组新键中

Python - 如何将现有字典添加到一组新键中

交互式爱情 2022-07-19 20:20:40
我的函数给了我以下格式的字典-{  "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 ...”
查看完整描述

1 回答

?
忽然笑

TA贡献1806条经验 获得超5个赞

我会复制字典,将原始键作为值与 reference 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


查看完整回答
反对 回复 2022-07-19
  • 1 回答
  • 0 关注
  • 111 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号