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'} 
1

4 Answers 4

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 
Sign up to request clarification or add additional context in comments.

Comments

1
if 'b' in map(str.lower, d.values()): ... 

3 Comments

Better use imap and dict.itervalues(), as it returns an iterator.
@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 :)
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: stackoverflow.com/q/11963711/846892
0
if filter(lambda x:d[x] == 'B', d): print "B is present else: print "b is not present" 

1 Comment

Question is about case-insensitive search.
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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.