2

I tried:

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

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

For me B is equal to b, but I don't want change my dictionary.

It is possible test for case insensitive matches against the values of a dictionary?

How to check if 'B' is present in the dictionary without changing the values?

#

More complex:

d = {3:'A',2:'B',6:'c'}
user7172
  • 874
  • 4
  • 16
  • 31
  • 2
    You can also make a case insensitive dict: http://stackoverflow.com/questions/2082152/case-insensitive-dictionary – alecxe Sep 06 '13 at 10:04

4 Answers4

3

You'd have to loop through the values:

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

For Python 3, replace .itervalues() with .values(). This tests the minimum number of values; no intermediary list is created, and the any() loop terminates the moment a match is found.

Demo:

>>> d = {3:'a',2:'b'}
>>> if any('B' == value.upper() for value in d.itervalues()):
...     print 'Yup'
... 
Yup
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1
if 'b' in map(str.lower, d.values()):
   ...
Viktor Kerkez
  • 45,070
  • 12
  • 104
  • 85
  • Better use `imap` and `dict.itervalues()`, as it returns an iterator. – Ashwini Chaudhary Sep 06 '13 at 10:06
  • @AshwiniChaudhary this is cleaner, and will work lazy on python 3. I doubt that he has a dictionary of more than 1.000.000 values so it shouldn't matter that much :) – Viktor Kerkez Sep 06 '13 at 10:09
  • Yes in py3.x `map` already returns an iterator, but in py2.x it'll create a list first and then it'll look for `'b'` in it. Related: http://stackoverflow.com/q/11963711/846892 – Ashwini Chaudhary Sep 06 '13 at 10:11
0
if filter(lambda x:d[x] == 'B', d):
  print "B is present
else:
  print "b is not present"
Smita K
  • 94
  • 5
0

Try this ..

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)
Djay
  • 9
  • 2