Python, comparing identical strings return False -
i'm aware many questions of kind posted here, couldn't find 1 matches case.
i have list made of dictionaries, each dictionary contains single key, , list value. example: keylist = [{'key1': [1,2,3]}, {'key2': [3, 4, 5]}, ...]
now, want create simple function receives 2 arguments: aforementioned list, , key, , returns matching dictionary given list.
the function is:
def foo(somekey, somelist): in somelist: if str(i.keys()).lower() == str(somekey).lower(): return
when called: foo('key1', keylist)
, function returned none object (instead of {'key1': [1,2,3]}
.
the 2 compared values have the same length , of same type (<type 'str'>
), yet comparison yields false value.
thanks advance assistance or/and suggestions nature of problem.
dict.keys()
returns list in python 2 , view object in python 3, you're comparing string representation string passed here. instead of can use in
operator check if dictionary contains key somekey
, want case insensitive search you'll have apply str.lower
each key first:
def foo(somekey, somelist): in somelist: if somekey.lower() in (k.lower() k in i): return
also if dicts contains single key can key name using iter()
, next()
:
>>> d = {'key1': [1,2,3]} >>> next(iter(d)) 'key1'
so, foo
be:
def foo(somekey, somelist): in somelist: if somekey.lower() == next(iter(i)).lower(): return
Comments
Post a Comment