迭代一组字典 - python - 基本搜索

时间:2013-01-23 05:51:59

标签: python search set dictionary

我发生了一件非常奇怪的事情。我试图遍历一组字典,以查找具有与字段键相关的特定值的所有项目。请采取以下措施:

ex_set是我无法控制的mysql系统的输出。如果我不得不使用python重新创建它,它将类似于:

dict_a [ 'field' ] = 'fruit'
dict_a [ 'value' ] = 'apple'
dict_b [ 'field' ] = 'fruit'
dict_b [ 'value' ] = 'berry'
ex_set = set()
ex_set.add (dict_a,dict_b)

重要的是当我打印它时该集合的外观。

pprint (ex_set)
OUTPUTS> ({'field' : 'fruit',
        'value' : 'apple'},
        'field' : 'fruit'},
        'value' : 'berry'})

i = 0
while len ( ex_set ) > i:
    for k , v in ex_set [i].iteritems ( ):
        if v == 'fruit':
        pprint ( ex_set[i] )
    i += 1

问题在于打印此内容并不会打印所有具有值=“水果”的词典。

有没有更好的方法来搜索一组词典?我正在搜索的集合在每个字典中有3个键/值组合和大约30k字典。这大约有25%的时间是有效的,我无法弄清楚为什么它只返回大约20%的比赛。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

根据您的描述,您正在寻找以下内容:

In [6]: ex_set = ({'fruit':'apple',
   ...:            'value':'fruit'},
   ...:           {'fruit':'fruit'},
   ...:           {'apple':'apple'})

In [7]: for d in ex_set:
   ...:     if 'fruit' in d.values():
   ...:         print(d)
   ...:         
{'fruit': 'apple', 'value': 'fruit'}
{'fruit': 'fruit'}

另外,除了事实之外,你的例子不是有效的python,ex_set肯定不能是set,因为sets's不能包含dictionaries,因为它们是不可用的。我会考虑将其重命名为更合适的东西:

In [8]: set([{}])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-7facc835553f> in <module>()
----> 1 set([{}])

TypeError: unhashable type: 'dict'