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
faces_encodings[location][name] = encoding, first check whether location is present in the dictionary or not byif location1 in dict1.keys()and if yes then check fornamein faces_encodings[location], if yes, then append it, not assign it.