3

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

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

问题是 this 的打印不会打印所有具有 value = "fruit" 的字典。

有没有更好的方法来搜索一组字典?我正在搜索的集合在每个字典和大约 30k 字典中有 3 个键/值组合。这大约有 25% 的时间有效,我不知道为什么它只返回大约 20% 的匹配项。

谢谢您的帮助!

4

1 回答 1

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 当然不能是 a 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'
于 2013-01-23T06:06:40.493 回答