【问题标题】:It is possible skip case sensitive in dict?在dict中是否可以跳过区分大小写?
【发布时间】:2013-09-06 10:02:01
【问题描述】:

我试过了:

d = {3:'a',2:'b'}

if 'B' in d.values():
    print 'True'

对我来说 B 等于 b,但我不想更改我的字典。

是否可以根据字典的值测试不区分大小写的匹配项?

如何在不更改值的情况下检查字典中是否存在'B'

#

更复杂:

d = {3:'A',2:'B',6:'c'}

【问题讨论】:

标签: python dictionary case-sensitive


【解决方案1】:

您必须遍历这些值:

if any('B' == value.upper() for value in d.itervalues()):
    print 'Yup'

对于 Python 3,将 .itervalues() 替换为 .values()。这会测试最小数量的值;没有创建中间列表,any() 循环在找到匹配项时终止。

演示:

>>> d = {3:'a',2:'b'}
>>> if any('B' == value.upper() for value in d.itervalues()):
...     print 'Yup'
... 
Yup

【讨论】:

    【解决方案2】:
    if 'b' in map(str.lower, d.values()):
       ...
    

    【讨论】:

    • 最好使用imapdict.itervalues(),因为它返回一个迭代器。
    • @AshwiniChaudhary 这更干净,并且会在 python 3 上懒惰地工作。我怀疑他有超过 1.000.000 个值的字典,所以它应该没那么重要:)
    • Yes 在 py3.x 中 map 已经返回了一个迭代器,但在 py2.x 中它会先创建一个列表,然后它会在其中查找 'b'。相关:stackoverflow.com/q/11963711/846892
    【解决方案3】:
    if filter(lambda x:d[x] == 'B', d):
      print "B is present
    else:
      print "b is not present"
    

    【讨论】:

    • 问题是关于不区分大小写的搜索。
    【解决方案4】:

    试试这个..

    import sys
    
    d = {3:'A',2:'B',6:'c'}
    letter = (str(sys.argv[1])).lower()
    
    if filter(lambda x : x == letter ,[x.lower() for x in d.itervalues()]):
        print "%s is present" %(letter)
    else:
        print "%s is not present" %(letter)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      相关资源
      最近更新 更多