【问题标题】:Iterate through set of dictionaries - python - basic search遍历字典集 - python - 基本搜索
【发布时间】:2013-01-06 13:17:03
【问题描述】:

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

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% 的匹配项。

感谢您的帮助!

【问题讨论】:

  • 贴一个更好的例子,ex_set 是无效的python。
  • 这不可能是实际代码...因为它不起作用。

标签: python search set dictionary


【解决方案1】:

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

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'

【讨论】:

  • 谢谢。 d.values 确实是我想要的。
  • sets's cant contain dictionaries as they are unhashable:有点不正确。如果你有di={1:'one',2:'two'},你可以做set(di)。它将根据字典的键创建一个集合。 set(di)==set(dickeys()) 是真的。
  • @drewk -- 怎么不正确,因为它将是一组值而不是一组字典。你不能有一个包含字典的集合。
  • @root:它不是包含字典的集合。它是字典键的一组可散列值。根据定义,字典的键是可散列的。试试代码! &gt;&gt;&gt; di={1:'one',2:'two'}; set(di)==set(di.keys()) 这将打印True 也可以尝试&gt;&gt;&gt; set({1:'one',2:'two'}) 这将打印{1, 2}
  • @drewk - 你的例子都是正确的,但 OP 说他有一套不可能的字典。我只是说你不能有一个包含 dict 的集合,而不是你不能将一个 dict 转换为一个包含它的键的集合。这都是两个独立的问题。
猜你喜欢
  • 2010-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-30
  • 2013-07-21
  • 1970-01-01
相关资源
最近更新 更多