【发布时间】:2020-05-01 05:04:07
【问题描述】:
自从我使用 Python(使用 3.8)以来已经有一段时间了,我一直在尝试组合一个快速而肮脏的工具来从文本文件中读取,删除一定范围内的键/值对,然后从中创建一个新的 JSON 文件。我主要不确定如何访问字典中选定范围的键/值的索引,而不是以我可以修改任何内容的方式浏览整个内容。这就是我要说的:
new_data = []
with open('edu01.txt') as json_file:
the_data = json.load(json_file)
for obj in the_data:
new_obj = {}
for key, val in obj.items():
new_obj[key] = val
# TypeError: cannot unpack non-iterable int object
for cut_key, cut_val in range(2, len(new_obj.items()) - 8):
new_obj.remove(cut_key, cut_val)
new_data.append(new_obj)
【问题讨论】:
-
您的意思是删除范围内的键还是范围内的字典索引?
-
范围内的键。因此,如果我有一本长度为 40 的字典,我想删除从索引 2 到索引 n 的所有内容,其中 n 小于 40
标签: python json loops file dictionary