【问题标题】:Loop list of dictionaries and delete/extract elements with key condition using Python使用 Python 循环字典列表并删除/提取具有关键条件的元素
【发布时间】:2023-01-12 19:07:23
【问题描述】:

我有一个字典列表,如下所示:

dict_list=[
    {
      "notes": [
          {"Id": "Id1","val": -1},
          {"Id": "Id2","val": 0},
          { "Id": "Id3","val": 1}
              ],
      "user_id": "u_id1"
    },
    {
      "notes": [
          {"Id": "Id4","val": -1},
          {"Id": "Id5","val": 1}
              ],
      "user_id": "u_id2"
    },
    {
      "notes": [
          {"Id": "Id4","val": 0}
              ],
      "user_id": "u_id3"
    }
  ]

我想编写一个函数,如果“val”=0 关于“notes”键,它应该检查并删除输入(dict_list)中的元素。 预期输出:

dict_list_new=[
    {
      "notes": [
          {"Id": "Id1","val": -1},
          { "Id": "Id3","val": 1}
              ],
      "user_id": "u_id1"
    },
    {
      "notes": [
          {"Id": "Id4","val": -1},
          {"Id": "Id5","val": 1}
              ],
      "user_id": "u_id2"
    }
  ]

谢谢你。

【问题讨论】:

  • 也许发布代码。
  • 您对此有何疑问?

标签: python list dictionary


【解决方案1】:

dict_list_new = []
for item in dict_list:
    note_list = []
    for note_item in item['notes']:
        if note_item['val'] != 0:
            note_list.append(note_item)
    if note_list:
        dict_list_new.append({
            'notes': note_list,
            'user_id': item['user_id'],
        })

【讨论】:

    【解决方案2】:

    你可以分两步完成

    1. 删除值为0的注释
    2. 删除带有空注释的对象
      
      def removeZero(obj):
          obj['notes'] = list(filter(lambda x: x['val'] != 0, obj['notes']))
          return obj
       
      dict_list = map(removeZero, dict_list)  #removes zeroes
      
      
      def hasNotes(obj):
          return len(obj['notes']) != 0
      
      dict_list = list(filter(hasNotes, dict_list))  #removes obj with empty notes
      
      print(dict_list)
      
      

      也可以一步完成,不过贴出来方便理解

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2023-03-21
      相关资源
      最近更新 更多