我希望使用用户输入来引用字典,以便用户选择要使用的字典。
例如,给定字典
cisco = {'uname': 'user_name', 'password': 'pass', 'backup_make': 'Write memory', 'backup_location_device': 'nvram:/startup-config'};
bnt = {'uname': 'user_name', 'password': 'pass', 'backup_make': 'save', 'backup_location_device': 'getcfg'};
ods = {'uname': 'user_name', 'password': 'pass', 'backup_make': 'None', 'backup_location_device': '/config/juniper.conf.gz'};
f5 = {'uname': 'user_name', 'password': 'pass', 'backup_make': 'tmsh save /sys ucs my.config.ucs', 'backup_location_device': '/var/local/ucs/my.config.ucs'};
hp = {'uname': 'user_name', 'password': 'pass', 'backup_make': 'save', 'backup_location_device': '/config.cfg'};
juniper = {'uname': 'user_name', 'password': 'pass', 'backup_make': 'None', 'backup_location_device': '/config/juniper.conf.gz'};
alteon = {'uname': 'user_name', 'password': 'pass', 'backup_make': 'save', 'backup_location_device': 'getcfg'};我想做这样的事
vendor = raw_input("Enter the vendor's name: ")
print ("the username: " + vendor["uname"] +
"; the password is: " + vendor["password"])我想使用“思科”,"bnt","ods“等索引,而不使用if语句。
谢谢!
发布于 2014-05-25 07:45:40
为什么不反过来做呢?
vendors = {'cisco': {'uname': 'user_name'...}
'bnt': {...}}然后,这样做:
requested_vendor = raw_input('Enter vendor name: ')
credentials = vendors.get(requested_vendor.lower())
if credentials:
print('The username is {} the password is {}'.format(credentials['uname'],
credentials['password']))
else:
print("Sorry, there is no vendor by the name {}".format(requested_vendor))发布于 2014-05-25 07:42:53
把它们都放进更大的字典里。
vendors = {
'cisco': cisco,
'bnt': bnt,
...
}
choice = vendors[vendor]发布于 2014-05-25 07:47:44
维护一个字典供应商,其键作为供应商名称,值作为供应商dict。价值
>> vendors = {}
>> vendor1 = {'uname': 'xyz', 'pass': 'abc'}
>> vendor2 = {'uname': 'abc', 'pass': 'xyz'}
>> vendors['vendor1'] = vendor1
>> vendors{'vendor2']= vendor2
>> vendor = raw_input().lower()
>> if vendor in vendors.keys():
.. print "The username is " + vendors[vendor]['uname'] + 'and the password is' + vendors[vendor]['pass']
>> else: print "%s not found" %vendorhttps://stackoverflow.com/questions/23853112
复制相似问题