Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access python dictionary with case insensitive string [duplicate]

I am struggling to see if there exist a way in order to access a python dictionary with strings as keys with the correct string but case insensitive

For example with this code:

dictionary = {'one': 1, 'two': 2, 'three', 3}
list = ['One', 'second', 'THree']

for item in list:
    if item in dictionary:
        print(item)

I am not able to find a way such that the output is: `One THree', ie. to compare the keys of the dictionary and the string that I have case insenstively

Is there a way to do that?

like image 847
Andrea Foderaro Avatar asked Aug 12 '26 01:08

Andrea Foderaro


1 Answers

You need to handle case-insenstivity on your end by either converting your dictionary.keys() to lower case or list elements to lower case or both as:

for item in list:
    if item.lower() in map(str.lower, dictionary.keys()):
        print(item)

You can either use lower() or upper(), but you have to be consistent in both the cases.

like image 118
ZdaR Avatar answered Aug 14 '26 14:08

ZdaR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!