【问题标题】:Looping over nested dictionary and delete if condition is not met (python)循环嵌套字典并在不满足条件时删除(python)
【发布时间】:2019-02-20 13:44:30
【问题描述】:

我有一个嵌套字典列表:

[{'a': 1,
  'b': 'string',
  'c': [{'key1': 80,
         'key2': 'string',
         'key3': 4033},
        {'key1': 324,
         'key2': 'string',
         'key3': 4034,
         'key4': 1}]},
 {'a': 1,
  'b': 'string',
  'c': [{'key1': 80,
         'key2': 'string',
         'key3': 4033},
        {'key1': 324,
         'key2': 'string',
         'key3': 4034,
         'key4': 1,
         'key5': 2}]}]

请注意,c 键的值又是一个字典列表。 现在我想从这个列表中过滤掉所有关键字为c的字典,它们不包含key1key2key3key4

我想先循环遍历列表中的第一个、第二个等dict,然后循环遍历以c 为键的嵌套dicts。然后,如果c里面的dict不符合我的要求,我就删除它。

因此我的代码是:

for j in range(len(mydict)):
    for i in range(len(mydict[j]["c"])):
        if not all (k in mydict[j]["c"][i] for k in ("key1", "key2", "key3", "key4")):
            del(mydict[j]["c"][i])

但我收到IndexError: list index out of range 错误。我的错在哪里?

我想要的输出是:

[{'a': 1,
  'b': 'string',
  'c': [{'key1': 324,
         'key2': 'string',
         'key3': 4034,
         'key4': 1}]},
 {'a': 1,
  'b': 'string',
  'c': [{'key1': 324,
         'key2': 'string',
         'key3': 4034,
         'key4': 1,
         'key5': 2}]}]

【问题讨论】:

  • 请添加您想要的输出,而不仅仅是您希望代码执行的粗略描述。
  • 从上面的字典中,你想要哪种类型的输出??所以请在你的问题中添加你想要的输出..

标签: python list dictionary for-loop


【解决方案1】:

问题在于,使用 for i in range(len(mydict[j]["c"])): 您正在迭代 dict 中的列表,同时从这些列表中删除。相反,您可以用列表推导替换内部循环:

for d in mydict:
    d['c'] = [d2 for d2 in d['c']
                 if all(k in d2 for k in ("key1", "key2", "key3", "key4"))]

【讨论】:

    【解决方案2】:

    只是为了有另一个选择:

    keep = {'key1', 'key2', 'key3', 'key4'}
    for h in mydict:
        h['c'] = [ e for e in h['c'] if len(keep - set(e.keys())) == 0 ]
    

    【讨论】:

      【解决方案3】:

      如果你想换个角度看:

      def remove_keys(mydict):
          mydict2 = mydict
          keys = ['key1', 'key2', 'key3', 'key4']
          for xIndex, x in enumerate(mydict):
              for yIndex, y in enumerate(x['c']):
                  if not all(key in y.keys() for key in keys):
                      del mydict2[xIndex]['c'][yIndex]
          return mydict2
      

      返回带有修改的新字典。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        相关资源
        最近更新 更多