如何允许用户在Python中过滤元组

时间:2017-04-28 17:24:05

标签: python dictionary

我目前有一个字典,结构如下:

{
    (foo, bar, baz): 1,
    (baz, bat, foobar): 5
}

在此结构中,键是表示条目属性的元组。在字典之外,我有另一个元组:

(property1, property2, property3)

这直接映射到字典的键。我希望用户能够根据属性输入过滤器以获取字典中的相关键。理想情况下,这也将采用字典的形式。例如,如果用户输入{property1: foo},程序将返回:

{
    (foo, bar, baz): 1
}

1 个答案:

答案 0 :(得分:1)

这当然是可能的,但我的实施并不像我希望的那样干净。基本方法是构造一个中间字典matcher,它包含要作为键匹配的元组索引及其对应的字符串(或者你有什么)作为值。

def get_property_index(prop):
    try:
        if prop.startswith('property'):
            # given 'property6' returns the integer 5 (0-based index)
            return int(prop[8:]) - 1
        else:
            raise ValueError

    except ValueError:
        raise AttributeError('property must be of the format "property(n)"')

def filter_data(data, filter_map):
    matcher = {}
    for prop, val in filter_map.items():
        index = get_property_index(prop)
        matcher[index] = val

    filtered = {}
    for key, val in data.items():
        # checks to see if *any* of the provided properties match
        # if you want to check if *all* of the provided properties match, use "all"
        if any(key[index] == matcher[index] for index in matcher):
            filtered[key] = val

    return filtered

下面给出了一些示例用法,它应该与请求的用法相匹配。

data = {
    ('foo', 'bar', 'baz'): 1,
    ('foo', 'bat', 'baz'): 2,
    ('baz', 'bat', 'foobar'): 3
}

filter_map1 = {
    'property1': 'foo'
}

print filter_data(data, filter_map1)
# {('foo', 'bar', 'baz'): 1, ('foo', 'bat', 'baz'): 2}

filter_map2 = {
    'property2': 'bat'  
}

print filter_data(data, filter_map2)
# {('foo', 'bat', 'baz'): 2, ('baz', 'bat', 'foobar'): 3}

filter_map3 = {
    'property2': 'bar',
    'property3': 'foobar'
}

print filter_data(data, filter_map3)
# {('foo', 'bar', 'baz'): 1, ('baz', 'bat', 'foobar'): 3}