如何根据键值是否存在的条件将元素追加到列表中?

2024-04-18 07:29:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,里面有

'Metadata/Location/Room'
'Metadata/Location/Building'

在用这些值附加新列表之前,我需要检查key('Metadata/Location/Room')是否存在于dict中(对于每个条目)。你知道吗

如何遍历dict,检查键是否存在,然后将其附加到新列表中?你知道吗

提前谢谢


Tags: key列表字典条目locationdictroommetadata
1条回答
网友
1楼 · 发布于 2024-04-18 07:29:41

查看tryexcept 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)一个键。比如:

to_keep = []
try:
    to_keep.append(key)
except KeyError:
    pass

相关问题 更多 >