如何在考虑特定约束的情况下搜索嵌套字典

时间:2012-02-02 19:34:31

标签: python search dictionary

希望有人可以提出一种简单的方法,以非常具体的方式搜索大型嵌套字典。

dict的例子:

foo = {"item1" : ((0.1, 0.03 , 0.7), (0.01, 0.01, 0.02), (0.3, 0.4, 0.05)), "item2" : ((0.5, 0.2 , 0.01), (0.1, 0.3, 1.0), (0.4, 0.2, 0.8))}

我想使用两个约束来搜索上面的内容。元组的位置和一个范围,用于搜索并返回任何匹配结果及其在列表中的索引位置及其对应的dict键,其中键值是真实索引位置的列表。

示例:使用范围(0.7-1.0)搜索元组的位置2,我想要一个字典:

{"item1" : (0), "item2" : (1, 2)}

我不确定如何使用约束运行搜索并按照我想要的方式格式化结果。任何建议都会很棒吗?非常感谢。

3 个答案:

答案 0 :(得分:2)

您可以定义自己的功能:

def special_search(my_dict, pos, min, max):
    result = {}
    for item, tuples in my_dict.items():
        matches = []
        for i, t in enumerate(tuples):
            if min <= t[pos] <= max:
                matches.append(i)
        if matches:
            result[item] = tuple(matches)
    return result

使用您的示例:

>>> foo = {"item1": ((0.1, 0.03 , 0.7), (0.01, 0.01, 0.02), (0.3, 0.4, 0.05)),
...        "item2": ((0.5, 0.2 , 0.01), (0.1, 0.3, 1.0), (0.4, 0.2, 0.8))}
>>> special_search(foo, 2, 0.7, 1.0)
{'item2': (1, 2), 'item1': (0,)}

答案 1 :(得分:1)

您还可以使用以下功能自定义测试:

from operator import itemgetter

test = lambda t: 0.7 <= itemgetter(2)(t) <= 1.0
results = dict((k, tuple(n for n,v in enumerate(t) if test(v))) for k,t in foo.items())

print(results)
# {'item2': (1, 2), 'item1': (0,)}

答案 2 :(得分:0)

更快更快的julio.alegria(+1)算法实现:

def search(d, pos, min, max):
    searchspace = set(range(min(max))
    answer = {}
    for k, v in d.iteritems():
        answer[k] = tuple([i for i,tuple in enumerate(v) if tuple[pos] in searchspace])
    return dict(( (k, d[k]) for k in in d if d[k]))