Check if a word exists in a dictionary doesn't find any word

后端 未结 1 797
孤独总比滥情好
孤独总比滥情好 2021-01-23 07:21

I want to find the dictionary contain that word or not. Word comes from the list is incrementing by a loop. Please give a suggestion if you\'re not getting question comment belo

相关标签:
1条回答
  • 2021-01-23 08:03

    You pinpointed the problem:

    if list[i] in d == True:
    

    list[i] in d == True chains operators in and == in short-circuit fashion (like (list[i] in d) and (d==True))

    Since d is different from True, global condition is always False and it seems that the word is not in the dictionary whereas it is.

    Either protect with parentheses (works, but ugly):

    if (list[i] in d) == True:
    

    or use pythonic truth test (never compare to True or False anyway, use in d or not in d):

    if list[i] in d:
    

    BTW as COLDSPEED noted, now that the statement works, you'll have an error here because d has no integer keys:

    print(d[i])   # d[list[i]] would be correct (but ugly)
    

    So rewrite your loop getting rid of the indexes while you're at it,directly iterating on the elements (and getting rid of list as a variable as this is the list type, switched to l):

    for item in l:
        if item in d:
            print(item)
    

    nicer right?

    0 讨论(0)
提交回复
热议问题