在Python中如何基于键中使用的正则表达式来查找字典中的元素?

2024-09-29 23:29:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用python定义了一个字典

  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()

Tags: keyselfclient元素datetimedate字典定义
1条回答
网友
1楼 · 发布于 2024-09-29 23:29:17

是和否。你可以通过检查所有的钥匙。但是使用字典的意义在于快速查找,也就是说,不必遍历所有的键,所以从这个意义上说你不能

如果你有选择的话,最好的解决方案是用不同的方式组织你的数据,制作一个有客户名字的字典。在clientnames下面,你放了另一本字典,上面键入了这些被损坏的名字。你把你的原始数据放在下面

示例实现:

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)

相关问题 更多 >

    热门问题