如何在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)
。