【问题标题】:Python deleting dict inside list inside dictPython在dict里面的list里面删除dict
【发布时间】:2023-03-09 20:39:01
【问题描述】:

我有一个配置文件,其中包含一些其他配置文件的列表,全部保存在 .json 中。
问题是,然后我尝试从列表中删除一个配置文件(因为不再需要它们)我不能使用 lsit.remove 和 del。

.json 文件:

{
  "version": "0.1",
  "trackers": [
    {
      "name": "some_sorter",
      "file_name": "C:/Users/c1v/Desktop/some_folder/fs_data/some_tracker_conf.json",
      "parent_folder": "C:/Users/c1v/Desktop/some_folder"
    },
    { # this is the dict I am trying to delete
      "name": "main_sort",
      "file_name": "main_sort.json",
      "parent_folder": "C:/Users/c1v/Desktop/main_folder_hehe"
    }
  ],
  "track_auto_run": [
    "example_name_of_tracker_conf_to_run_on_program_deploy.json",
    "second_one.json"
  ]
}

我正在使用的代码:

import shutil
import os
index = load_json("fs_data/index.json", "r")  # Load json and return it as dict

# shell[1] is equal to "main_sort"

not_found = True
for i in index['trackers']:
    if i['name'] == shell[1]:
        print(f"Found! {i}")
        not_found = False
        for f in os.listdir(i['parent_folder']):
            shutil.rmtree(os.path.join(i['parent_folder'], f))
            del index['trackers'][i]  # HERE is the problem
            save_json("fs_data/index.json", index, "w", indent=2)  # save dict to json. Args: file localizatin, data to save, mode to use (I know it's kinda pointless, but sometimes I need that for debuging, indent thet will be in file)
            break
if not_found:
    print("Failed to found!")

【问题讨论】:

标签: python json python-3.x list dictionary


【解决方案1】:

您无法在迭代列表时删除列表项。使用循环查找要删除的项目的索引,然后删除。类似的东西

import shutil
import os
index = load_json("fs_data/index.json", "r")  # Load json and return it as dict

# shell[1] is equal to "main_sort"

i_remove = -1
for j, i in enumerate(index['trackers']):
    if i['name'] == shell[1]:
        i_remove = j
        print(f"Found! {i}")
        break
else:
    print("Failed to found!")
if i_remove >= 0:
    i = index['trackers'][i_remove]
    for f in os.listdir(i['parent_folder']):
        shutil.rmtree(os.path.join(i['parent_folder'], f))
    del index['trackers'][i_remove]  # HERE is no problem
    save_json("fs_data/index.json", index, "w", indent=2)  # save

【讨论】:

  • 谢谢!这有很大帮助。如果有人会使用该代码,请注意。把 del 和 save_json 放在循环之外,我错了。
  • 你是对的,我只是复制粘贴了你的代码,没有检查语义。现在编辑我的答案以反映您的建议。
猜你喜欢
  • 2017-10-21
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多