问题描述
我有一本字典$session=$this->getController()->getRequest()->getSession()
:
dict
dict = {'drop_key1': '10001','drop_key2':'10002'}
中的密钥以dict
开头,我想通过从密钥中删除drop_
的值来更新dict
:
drop_
什么是最好的方法?
解决方法
类似
d1 = {'drop_key1': '10001','drop_key2':'10002'}
d2 = {k[5:]:v for k,v in d1.items()}
print(d2)
输出
{'key1': '10001','key2': '10002'}
,
一种方法是,对于字典中的每个key
值,您都可以用新的字符串值替换部分字符串。例如:
d = {k.replace('drop_',''): v for k,v in d.items() if k.strip().startswith('drop_')}
或者您可以定义一个函数,并获取搜索到的字符串的索引(“ drop_
”)。如果搜索字符串索引为0,则将其删除。例如:
def change_key(key,search):
start_idx = key.find(search)
if start_idx == 0:
key = key.replace(search,"")
return key
d = {change_key(k,search="drop_"): v for k,v in d.items()}
结果:
{'key1': '10001','key2': '10002'}
请注意,如果使用方法,则可以保证删除搜索字符串(如果它位于字符串的开头)。例如:
d = {' drop_key1': '10001','drop_key2': '10002'}
d = {change_key(k,v in d.items()}
结果:
{' drop_key1': '10001','key2': '10002'}