2024-04-18 07:29:41 发布
网友
我有一本字典,里面有
'Metadata/Location/Room' 'Metadata/Location/Building'
在用这些值附加新列表之前,我需要检查key('Metadata/Location/Room')是否存在于dict中(对于每个条目)。你知道吗
如何遍历dict,检查键是否存在,然后将其附加到新列表中?你知道吗
提前谢谢
查看try,except KeyError异常处理:
try
except KeyError
>>> d = {'a': 1, 'b': 2} >>> >>> for key in ['a', 'b', 'c']: ... try: ... d[key] += 1 ... except KeyError: ... print("'%s' not in the dictionary" % key) ... 'c' not in the dictionary
如果在列表中,您只需调整它以保留(appending)一个键。比如:
append
to_keep = [] try: to_keep.append(key) except KeyError: pass
查看
try
,except KeyError
异常处理:如果在列表中,您只需调整它以保留(
append
ing)一个键。比如:相关问题 更多 >
编程相关推荐