我在python中定义了一个Dictionary.And键的构造如下;
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'}
在上面的运行时我构建了密钥。我想在重置它时清除缓存中的某些元素。那时,我知道clientname参数。使用它作为正则表达式,我可以在缓存中找到元素吗?所以,我很容易清除它们。
我想做的是;
self.cacheDictionary[%clientname%].clear()
是的,不是。你可以通过所有的密钥。但是使用字典的重点是快速查找,即不必通过所有键,所以从这个意义上说你不能。
最佳解决方案 - 如果您有选择 - 将以不同方式组织您的数据,使用客户名称键入字典。在客户端名称下,您放置了另一个使用受损名称键入的字典。在那些你把原始数据。
示例实施:
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)
如果您的原始字典已修复,您仍然可以使用密钥客户端名称和值损坏的客户端名称创建查找字典。
示例实施:
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)