Yaki
Yaki

Reputation: 1

Python, comparing identical strings return False

I'm aware that many questions of the kind were posted here, but I couldn't find one that matches my case.

I have a list made up of dictionaries, where each dictionary contains only a single key, and a list as its value. For example: keyList = [{'key1': [1,2,3]}, {'key2': [3, 4, 5]}, ...]

Now, I want to create a simple function which receives two arguments: an aforementioned list, and a key, and returns a matching dictionary from a given list.

the function is:

def foo(someKey, someList):
    for i in someList:
        if str(i.keys()).lower() == str(someKey).lower():
            return i

When called: foo('key1', keyList), the function returned the None object (instead of {'key1': [1,2,3]}.

The two compared values have the the same length and are of the same type (<type 'str'>), yet a comparison yields a False value.

Thanks for advance for any assistance or/and suggestions as to the nature of the problem.

Upvotes: 0

Views: 1093

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

dict.keys() returns a list in Python 2 and view object in Python 3, so you're comparing their string representation with the string you passed here. Instead of that you can use the in operator to check if the dictionary contains the key someKey, as you want to do a case insensitive search you'll have to apply str.lower to each key first:

def foo(someKey, someList):
    for i in someList:
        if someKey.lower() in (k.lower() for k in i):
            return i

Also if your dicts always contains a single key then you can get the key name using iter() and next():

>>> d = {'key1': [1,2,3]}
>>> next(iter(d))
'key1'

So, foo will be:

def foo(someKey, someList):
    for i in someList:
        if someKey.lower() == next(iter(i)).lower():
            return i

Upvotes: 2

Related Questions