编辑:
从您下面的评论来看,您似乎正在尝试存储一组
host
记录,唯一键入
ip
和
hostname
.
您应该考虑将其存储在两层字典中,如下所示:
items = {
'10.0.0.1': {
'abc.com': {'record_type': 'a', ... },
'www.abc.com': {'record_type': 'cname', ... }
},
'10.0.0.2': {
'xyz.com': {'record_type': 'a', ... },
'www.xyz.com': {'record_type': 'cname', ... }
}
}
然后,您可以使用以下两个键值轻松访问任何项目:
def item_exists(ip, hostname):
return ip in items.keys() and hostname in items[ip].keys()
def get_item(ip, hostname):
return items[ip][hostname] if item_exists(ip, hostname) else None
def add_or_replace_item(ip, hostname, item):
if ip not in items.keys():
items[ip] = {}
items[ip][hostname] = item
def add_item_if_not_exists(ip, hostname, item):
if not item_exists(ip, hostname):
add_or_replace_item(ip, hostname, item)