import ipaddress


def ip_in_networks(ip, networks, min_prefix_len=1):
    """Return whether `ip` is in the dict of networks

    This is O(1) regardless of the size of networks

    Implementation based on netaddr.IPSet.__contains__

    Repeatedly checks if ip/32; ip/31; ip/30; etc. is in networks
    for all netmasks that match the given ip,
    for a max of 32 dict key lookups for ipv4.

    If all netmasks have a prefix length of e.g. 24 or greater,
    min_prefix_len prevents checking wider network masks that can't possibly match.

    Returns `(netmask, networks[netmask])` for matching netmask
    in networks, if found; False, otherwise.
    """
    if min_prefix_len < 1:
        raise ValueError(f"min_prefix_len must be >= 1, got {min_prefix_len}")
    if not networks:
        return False
    check_net = ipaddress.ip_network(ip)
    while check_net.prefixlen >= min_prefix_len:
        if check_net in networks:
            return check_net, networks[check_net]
        check_net = check_net.supernet(1)
    return False