简体   繁体   中英

re.findall() returns empty list in python?

I have python method defined as follows. I try to match dictionary elements which matches to clientname parameter

def loadSites(self, fpath, clientname):

            keylist = [re.findall(clientname,k) for k in self.cacheDictionary.keys()]
            for items in keylist:
                print(items)

When I print the list I get;

['testClient']
['testClient']
[]
[]
[]
[]

I expect to get only two elements. What Im doing wrong here?

Also, how Can I delete that item from my dictionary?

If you want only two elements return only when there is a match.

keylist = [re.findall(clientname,k) if(re.findall(clientname,k)) else None for k in self.cacheDictionary.keys()]
        for items in keylist:
            print(items)

re.findall returns an empty list if the pattern is not found. You can simply filter these out. Note that when you iterate a dict , you automatically iterate the keys:

keylist = filter(None, (re.findall(clientname,k) for k in self.cacheDictionary))
# Python3: if you want to persist a list
# keylist = list(filter(None, (re.findall(clientname,k) for k in self.cacheDictionary)))

for items in keylist:
    print(items)

Update:

If you want to delete all keys from the dict that match your pattern and in fact contain the string, there are many options tat do not require regular expressions, eg:

ks = [k for k in self.cacheDictionary if clientName in k]
for k in ks:
    self.cacheDictionary.pop(k)
    # del self.cacheDictionary[k]

Or just comprehend a new dict form scratch in one iteration:

self.cd = {k: v for k, v in self.cd.items() if clientName not in  k}

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