我遇到了一件非常奇怪的事情。我正在尝试遍历一组字典以查找具有与字段键相关的特定值的所有项目。采取以下措施:
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/