[Python] how to append data in nested dictionary in python

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    I have a to add a data in a nested dictionary, where nested keys names can be unknown so it should create new keys itself if it doesn't find one or else it should append it an existing key

    this is my logic

    if os.path.exists(str(base_path)+"/face_encodings.pickle"):
    with open(str(base_path) + "/face_encodings.pickle", 'rb') as handle:
    faces_encodings = pickle.load(handle)
    try:
    faces_encodings[location][name] = encoding
    except:
    faces_encodings[location] = {}
    faces_encodings[location][name] = encoding
    handle.close()
    print(faces_encodings)

    else:
    faces_encodings = {location:{}}
    with open(str(base_path) + "/face_encodings.pickle", 'wb') as handle:
    faces_encodings[location][name] = encoding
    pickle.dump(faces_encodings, handle, protocol=pickle.HIGHEST_PROTOCOL)
    handle.close()
    print(faces_encodings)


    In brief, suppose this is a dictionary looks like

    {
    location1:{
    id1:encoding1,
    id2:encoding2
    },
    location2:{
    id3:encoding3,
    id4:encoding4
    },
    location3:{
    id5:encoding5,
    id6:encoding6
    }
    }


    So by my logic code if I have to save new encoding of location which does not exist it should create a new or else push it into existing location nested dict, but the issue it's replacing the other ids data

    Continue reading...

Compartilhe esta Página