python - 遍历一组字典 - python - 基本搜索

标签 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

问题是打印这个并没有打印出所有值为“fruit”的字典。

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

感谢您的帮助!

最佳答案

根据您的描述,您正在寻找类似的东西:

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 不能包含 字典,因为它们是不可散列的。我会考虑将其重命名为更合适的名称:

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

TypeError: unhashable type: 'dict'

关于python - 遍历一组字典 - python - 基本搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14473297/

相关文章:

python - 对于这个特定的任务来说,字典或元组列表会更有效吗?

python - 在一行 if 语句 python 中正确使用 * 运算符

java - 如何从输入文件中获取某些文本的行号?

swift - 尝试在 Swift 5 中设置 UISearchController 的背景颜色

c# GetDirectories 返回意外目录(已给出具体示例)

python - 如何在 .hgignore 中模拟语言补码运算符?

python - 为什么 Python set([]) 不等于 {}?

linux - 如何让sqlplus的输出出现在一行中?

python - 迭代时从集合中删除项目

python - 递归调用中的退出子句