0

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

1
  • 1
    Instead of directly doing faces_encodings[location][name] = encoding, first check whether location is present in the dictionary or not by if location1 in dict1.keys() and if yes then check for name in faces_encodings[location], if yes, then append it, not assign it. Commented Dec 26, 2019 at 18:27

3 Answers 3

0

If I understand your question correctly, you could check if a key exists in a dictionary using the "in" keyword. For example, if you have a dict myDict = {"message":"Hello"} then this statement

if "message" in myDict:
   return true
else:
  return false

will return true.

Using this logic, you can then either 1) Create a new dict OR 2) Change the existing content of the nested dict by adding new key

Sign up to request clarification or add additional context in comments.

1 Comment

1) True and False are capitalised in Python. 2) You can condense that to just return 'message' in myDict.
0

The defaultdict is perfect for this. It automatically creates the dict values if they don't already exist.

from collections import defaultdict

d = defaultdict(dict)

d[location][name] = encoding

For example:

d = defaultdict(dict)
d['giraffe']['description'] = 'tall'
d['giraffe']['legs'] = 4
d['fish']['legs'] = 0

# > defaultdict(dict,
# >            {'giraffe': {'description': 'tall', 'legs': 4},
# >             'fish': {'legs': 0}})

3 Comments

hey thanks for helping,I used defaultdict if os.path.exists(str(base_path)+"/face_encodings.pickle"): with open(str(base_path) + "/face_encodings.pickle", 'rb') as handle: faces_encodings = defaultdict(lambda : pickle.load(handle)) if location in faces_encodings.keys(): if name in faces_encodings[location].keys(): else: faces_encodings[location][name] = encoding ,but its still replacing whole data,is this a wrong way to use
Please edit your post with that information, not the comment. Comments do not allow code blocks.
It looks like you've got defaultdict(lambda: pickle.load(handle)). You should have defaultdict(dict).
0
faces_encodings.setdefault(location, {}).setdefault(name, encoding)

1 Comment

This is a very incomplete answer. Add some explanation to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.