【问题标题】:Check for a key pattern in a dictionary in python检查python字典中的键模式
【发布时间】:2011-04-13 17:50:59
【问题描述】:
    dict1=({"EMP$$1":1,"EMP$$2":2,"EMP$$3":3})

如何使用python检查字典中是否存在EMP

   dict1.get("EMP##") ??

【问题讨论】:

  • 目前还不完全清楚您要做什么。你能改写你的问题吗?提供样本输入和输出会有所帮助。

标签: python dictionary string-matching


【解决方案1】:

你想做什么并不完全清楚。

您可以使用the startswith() method 循环选择dict 中的键:

>>> for key in dict1:
...     if key.startswith("EMP$$"):
...         print "Found",key
...
Found EMP$$1
Found EMP$$2
Found EMP$$3

您可以使用列表推导来获取所有匹配的值:

>>> [value for key,value in dict1.items() if key.startswith("EMP$$")]
[1, 2, 3]

如果您只想知道某个键是否匹配,您可以使用the any() function

>>> any(key.startswith("EMP$$") for key in dict1)
True

【讨论】:

  • 我在你的第一个例子中试过这个,我在它后面放了一个 else,if 部分条件似乎是错误的......
  • 我尝试了这种方法,它按作者的意图工作。添加一个 else 也适用于我。你遇到了什么错误?
【解决方案2】:

这种方法让我觉得与字典的意图相反。

字典由哈希键组成,哈希键具有与之关联的值。这种结构的好处是它提供了非常快速的查找(大约 O(1))。通过搜索密钥,您将否定该好处。

我建议重新组织你的字典。

dict1 = {"EMP$$": {"1": 1, "2": 2, "3": 3} }

那么,找到“EMP$$”就这么简单

if "EMP$$" in dict1:
    #etc...

【讨论】:

    【解决方案3】:

    您需要更具体地说明您想做什么。但是,假设您提供的字典:

     dict1={"EMP$$1":1, "EMP$$2":2, "EMP$$3":3}
    

    如果您想在尝试请求之前知道是否存在特定密钥,您可以:

    dict1.has_key('EMP$$1') 
    True
    

    返回True,因为dict1 有一个密钥EMP$$1

    您也可以忘记检查键并依赖默认返回值dict1.get()

    dict1.get('EMP$$5',0)
    0
    

    返回 0 作为默认值,因为 dict1 没有密钥 EMP$$5

    以类似的方式,您还可以使用 `try/except/ 结构来捕获和处理丢失的键:

    try:
        dict1['EMP$$5']
    except KeyError, e:
        # Code to deal w key error
        print 'Trapped key error in dict1 looking for %s' % e
    

    这个问题的其他答案也很好,但我们需要更多信息才能更准确。

    【讨论】:

    【解决方案4】:

    没有办法像这样匹配字典键。我建议你重新考虑这个问题的数据结构。如果这必须特别快,您可以使用后缀树之类的东西。

    【讨论】:

      【解决方案5】:

      您可以使用in 字符串运算符来检查项目是否在另一个字符串中。 dict1 迭代器返回键列表,因此您检查每个 dict1.key 的“EMP$$”。

      dict1 = {"EMP$$1": 1, "EMP$$2": 2, "EMP$$3": 3}
      
      print(any("EMP$$" in i for i in dict1))
      # True
      
      # testing for item that doesn't exist
      print(any("AMP$$" in i for i in dict1))
      # False
      

      【讨论】:

        猜你喜欢
        • 2019-04-19
        • 2016-11-14
        • 1970-01-01
        • 2019-03-29
        • 1970-01-01
        • 1970-01-01
        • 2020-05-14
        • 2017-06-23
        • 2020-07-05
        相关资源
        最近更新 更多