如何检查多维字典中是否存在值?

时间:2018-05-20 00:47:02

标签: python-3.x lambda

具有关联主机和IP地址的多维字典,例如:

items = {
    '10.0.0.1': [
        { 'host': 'abc.com', 'record_type': 'a', ... },
        { 'host': 'www.abc.com', 'record_type': 'cname', ... }
    ]
}

我有一个新的主机和IP地址要添加到数组,但是,如何检查是否存在以防止重复?例如:需要将www.abc.com插入到10.0.0.1但没有cname, canot将对象的克隆用于in条件中的if而不使用record_type cname

使用lambda?但如果有主机和IP地址,如何使用lambda尝试获取对象?

1 个答案:

答案 0 :(得分:1)

编辑:

从下面的评论中,您似乎正在尝试存储一组host条记录,这些记录在iphostname上唯一关键字。

您应该考虑将这些存储在2层字典中,如下所示:

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)