Home > OS >  Loop list of dictionaries and delete/extract elements with key condition using Python
Loop list of dictionaries and delete/extract elements with key condition using Python

Time:01-12

I have a list of dictionaries as shown below:

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"
    }
  ]

I would like to write a function which should check and remove elements inside the input (dict_list) if "val"=0 regarding to "notes" key. Expected output:

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"
    }
  ]

Thank you.

CodePudding user response:

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'],
        })

CodePudding user response:

you can do it in two steps

  1. remove the notes with value 0
  2. remove the objects with empty notes

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)

It can be done in one step as well, but posting this for easy understanding

  • Related