简体   繁体   中英

Python Error in else syntax

I have the following python code:

def myFunction(myDictionary, query):
    D=set() 
    for i in range(len(query)):
        if query[i] in myDictionary.keys():
            if i==0:
                D.update((myDictionary[query[i]])
            else:
                D.intersection_update(myDictionary[query[i]])
    return D

myDictionary contains dictionary items as follows: {'first':{0,1,2}, 'second':{5,2,1}, ..etc} . The query contains al list of words, eg ['first','second',..ect,] I want to return the intersection of all the query words. For example, if query=['first','second'] and myDictionary={'first':{0,1,2}, 'second':{5,2,1}} , then my result set should be the intersection which is: {1,2} .

When I run my code, I get a syntax error in the else statement. I added if i==0 because otherwise my result set D will always be empty set. I do not see what is wrong in my code.

You are missing a closing parethesis:

D.update((myDictionary[query[i]])
# 2 open ^ but only one close ---^

Python cannot detect the missing parenthesis until the next line, where the else: statement is unexpected.

You only need one pair of parenthesis there:

D.update(myDictionary[query[i]])

You also do not need to call .keys() to do a membership test on a dictionary:

if query[i] in myDictionary:

is enough.

You probably want to loop directly over the query list and use enumerate() instead:

for i, q in enumerate(query):
    if q in myDictionary:
        if not i:
            D.update(myDictionary[q])
        else:
            D.intersection_update(myDictionary[q])

or switch to using a generator expression:

def myFunction(myDictionary, query):
    matches = (myDictionary[q] for q in myDictionary.viewkeys() & query)
    try:
        D = {next(matches)}  # start with the first match
    except StopIteration:
        # Nothing matched
        return set()
    D.intersection_update(*matches)
    return D

Use .keys() if you are using Python 3; .viewkeys() in Python 2 and .keys() in Python 3 return dictionary view objects which, for keys at least, act like sets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM