【问题标题】:Searching key/values with defaultdict使用 defaultdict 搜索键/值
【发布时间】:2012-01-18 12:09:38
【问题描述】:

我熟悉 iteritems() 和 items() 与标准字典的使用,它可以与 for 循环结合使用来扫描键和值。但是,我怎样才能最好地使用默认字典来做到这一点。例如,我想检查给定值是否未显示在键或与任何键关联的任何值中。我目前正在尝试以下方法:

for key, val in dic.iteritems():
    print key, val

但是我得到以下信息:

1 deque([2, 2])

我对变量/字典有以下声明

from collections import defaultdict, deque
clusterdict = defaultdict(deque)

那么我怎样才能最好地获得关键价值呢?谢谢!

【问题讨论】:

  • 确定你想要什么,dic.keys() / dic.values() ?
  • 你确实得到了价值。您将获得与 1 的键关联的双端队列对象。你得到的有什么问题?

标签: python defaultdict


【解决方案1】:

一般来说,对于一个默认字典dd,要检查一个值x是否被用作键,这样做:

x in dd

要检查 x 是否用作值,请执行以下操作:

x in dd.itervalues()

在您的情况下(以双端队列为值的默认字典),您可能想查看 x 是否在任何双端队列中:

any(x in deq for deq in dd.itervalues())

请记住,defaultdicts 的行为类似于常规字典,只是它们在对丢失的键进行d[k] 查找时自动创建新条目;否则,它们的行为与常规 dicts 没有什么不同。

【讨论】:

    【解决方案2】:

    如果我理解了你的问题:

    for key, val in dic.iteritems():
        if key!=given_value and not given_value in val:
            print "it's not there!"
    

    除非你的意思是别的......

    【讨论】:

      【解决方案3】:

      我为 Python 3 制作了这个:

      from collections import defaultdict
      
      count_data = defaultdict(int)
      count_data[1] = 10
      query = 2
      if query in count_data.values():
         print('yes')
      

      编辑

      你也可以使用 Counter 字典:

      from collections import Counter
      count_data = Counter()
      count_data[1] = 10
      query = 2
      if query in count_data.values():
          print('yes')
      

      【讨论】:

        【解决方案4】:
        stuff = 'value to check'
        if not any((suff in key or stuff in  value) for key, value in dic.iteritems()):
            # do something if stuff not in any key or value
        

        【讨论】:

          【解决方案5】:

          【讨论】:

          • 如果你在 dict 中寻找一些值,更好的方法是 dict.get('key') 它返回值,如果没有这样的键则返回 None
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-28
          • 2015-05-13
          • 1970-01-01
          • 2017-09-08
          • 2017-01-13
          • 2015-07-10
          相关资源
          最近更新 更多