【问题标题】:Remove key/value pairs in a dictionary over a certain range在一定范围内删除字典中的键/值对
【发布时间】: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


【解决方案1】:
# 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)

在这部分,你不能解包range(2, len(new_obj.items()) - 8),因为它是range对象而不是dict对象,不知道范围的长度是不是2(如果长度是2,只有你可以解包)。

我认为,你的意图并不明确。你能写得更详细吗?比如像输入输出例子

【讨论】:

  • 例如,如果我的字典类似于{ State: AB, Population: 100, State Bird: toucan, ... Thirty-seventh: UV, Thirty-eighth: WX, Thirty-ninth: YZ }。我想摆脱从第三个索引开始到第 38 个索引的所有内容,这样我最终只得到{ State: AB, Population: 100, Thirty-ninth: YZ }
【解决方案2】:

在读取 json 文件时,您可能需要考虑使用 OrderedDict()。通过这种方式,您可以根据您的条件范围检查键的索引:

the_data = json.load(open('edu01.json'), object_pairs_hook=OrderedDict)

for idx, key in enumerate(reversed(the_data.keys())):
    if idx in range(len(the_data.items()) - 2, 8, -1):
        the_data.pop(key)

常规字典不会保留您的项目的顺序。虽然我不完全确定在 OrderedDictionaries 的情况下需要 reversed(),但最好向后工作以确保在删除索引时不会更改索引。或者,您可以这样做:

the_data = json.load(open('edu01.json'), object_pairs_hook=OrderedDict)
keys_to_remove = []

for idx, key in enumerate(reversed(the_data.keys())):
    if idx in range(len(the_data.items()) - 2, 8, -1):
        keys_to_remove.append(key)

for k in keys_to_remove:
    the_data.pop(k)

【讨论】:

  • 看起来你在做某事,但是当我玩弄它时,编辑抱怨.keys() 不起作用,因为the_data 是一个列表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2011-01-09
  • 2019-05-04
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多