简体   繁体   中英

Python dictionary optimize this script

I have a string like rdb_master_mongodb where rdb_ is fixed and master is a database name which can be anything and mongodb can be one among mysql , mongodb , postgres , mssql or bdb . I need to fetch the value for this string from the dictionary which has the value in myDict[master][mongodb] . In order to get this I need to split the string rdb_master_mongodb and get the values of master and mongodb . I can't use split because sometimes the string becomes rdb_master_test_mongodb . Hence I have to use endswith to get the exact key. Howeveer, endswith does not work on a list.

I have to get the matching tuple value from a tuple. Right now I do this like:

import re 
name = 'rdb_master_mongodb'
s = re.sub('rdb_', "", name)
VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb')
(a, b, c, d, e) = VALID_DB
if s.endswith(a):
   db = a
if s.endswith(b):
  db = b
if s.endswith(c):
  db = c
if s.endswith(d):
  db = d
if s.endswith(e):
  db = e
db_name = re.sub('_'+db, "", s)
print db_name+" is "+db

Is there a better way to do this?

db = name.rsplit('_', 1)[1]
if db not in VALID_DB:
    raise ValueError('Incorrect DB name: %s' % db)

If the format of name is always the same, you can split it into parts first:

rdb, temp = name.split('_', 1)
master, db = temp.rsplit('_', 1)

then check whether db is valid:

VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb')
if db in VALID_DB:
   ...

then use these three variables rdb, master, db to build needed strings.

So only the end of the word is significant, if I understand you well, in this case I'd try:

>>> VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb')
>>> name = 'rdb_master_mongodb'
>>> db_name = [db for db in VALID_DB if name.endswith(db)][0]
>>> db_name
'mongodb'
>>> name_test = 'rdb_master_test_mongodb'
>>> db_name = [db for db in VALID_DB if name_test.endswith(db)][0]
>>> db_name
'mongodb'

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