Ratha
Ratha

Reputation: 9692

How to find elements based on regular expression used in keys in a Dictionary in python?

I have defined a Dictionary in python.And keys are constructed like as follows;

  self.cacheDictionary = {}
  key = clientname + str(i)    
  self.cacheDictionary[key] = {'date_populated': str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")),'date_updated' :str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")),'client':clientname,
                           'site': dirs[i], 'state':'unprocessed', 'machine':'null'}

In the above at runtime I build keys. I want to clear certain elements in the cache when we reset it. At that time, I know clientname parameter. Using that as Regular expression, Can I locate elements in the Cache? So, easily I can clear them.

What I would like to do is;

self.cacheDictionary[%clientname%].clear()

Upvotes: 1

Views: 50

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53029

Yes and no. You can by going through all the keys. But the point of using a dictionary is fast lookup, i.e. not having to go through all the keys, so in that sense you can't.

The best solution - if you have the option - would be organizing your data differently, make a dictionary keyed with client names. Under the clientnames you put another dictionary keyed with the mangled names. Under those you put your original data.

Sample implementation:

import datetime
import time

cacheDictionary = {}
dirs = 'abcde'

for clientname in {'John Smith', 'Jane Miller'}:
    for i in range(5):
        key = clientname + str(i)    
        cacheDictionary.setdefault(clientname, {})[key]  = {'date_populated': str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")),'date_updated' :str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")),'client':clientname,'site': dirs[i], 'state':'unprocessed', 'machine':'null'}
        time.sleep(0.1)

import pprint

pprint.pprint(cacheDictionary)

If your original dictionary is fixed you could still make a lookup dictionary with keys client names and values mangled client names.

Sample implementation:

import datetime
import time

cacheDictionary = {}
dirs = 'abcde'

for clientname in {'John Smith', 'Jane Miller'}:
    for i in range(5):
        key = clientname + str(i)    
        cacheDictionary[key]  = {'date_populated': str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")),'date_updated' :str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")),'client':clientname,'site': dirs[i], 'state':'unprocessed', 'machine':'null'}
        time.sleep(0.1)

import re

discard_numbers = re.compile("(.*?)(?:[0-9]+)")

lookup = {}

for key in cacheDictionary.keys():
    clientname = discard_numbers.match(key).groups(1)
    lookup.setdefault(clientname, set()).add(key)

import pprint

pprint.pprint(lookup)

Upvotes: 1

Related Questions