Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python的嵌套字典中追加数据_Python_Python 3.x_Dictionary - Fatal编程技术网

如何在python的嵌套字典中追加数据

如何在python的嵌套字典中追加数据,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我需要在嵌套字典中添加一个数据,其中嵌套键的名称可能是未知的,因此如果找不到,它应该自己创建新键,否则它应该将其附加到现有键 这是我的逻辑 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)

我需要在嵌套字典中添加一个数据,其中嵌套键的名称可能是未知的,因此如果找不到,它应该自己创建新键,否则它应该将其附加到现有键

这是我的逻辑

 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)
简言之,假设这是一本字典

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

因此,根据我的逻辑代码,如果我必须保存不存在的位置的新编码,它应该创建一个新的或将其推入现有位置嵌套dict,但问题是,如果我正确理解您的问题,它将替换其他ID数据, 您可以使用“in”关键字检查字典中是否存在键。例如,如果您有一个dict
myDict={“message”:“Hello”}
,那么下面的语句

如果myDict中有“消息”:
返回真值
其他:
返回错误
将返回真值


使用此逻辑,您可以1)创建新的dict,或2)通过添加新键更改嵌套dict的现有内容
defaultdict
非常适合此操作。如果dict值不存在,它会自动创建dict值

from collections import defaultdict

d = defaultdict(dict)

d[location][name] = encoding
例如:

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}})

与其直接执行
faces\u encodings[location][name]=encoding
,不如先通过dict1.keys()中的location1检查字典中是否存在位置,如果是,则检查faces\u encodings[location]中的
name
,如果是,则追加它,而不是分配它。嘿,谢谢你的帮助,如果os.path.exists(str(base_path)+“/face_encodings.pickle”):使用open(str(base_path)+“/face_encodings.pickle”,“rb”)作为句柄:faces_encodings=defaultdict(lambda:pickle.load(handle))if location in faces\u encodings.keys():if name in faces\u encodings[location].keys():else:faces\u encodings[location][name]=编码,但它仍在替换整个数据,这是一种错误的使用方式吗请使用该信息而不是注释编辑帖子。注释不允许使用代码块。看起来您已经拥有了
defaultdict(lambda:pickle.load(handle))
。您应该有
defaultdict(dict)