2014-05-25 33 views
0

我想使用用户输入引用字典,以便用户将选择使用哪个字典。如何根据用户的选择选择字典?

例如,给定的字典

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”, “消耗臭氧层物质” 等作为指标而不使用if声明。

谢谢!

+1

更正您的数据结构,使用一个字典来嵌套所有7个字典 –

回答

2

为什么不这样做呢?

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)) 
+0

这是不正确的,密码是不通过的关键。 –

3

把它们放在一个更大的字典里面。

vendors = { 
    'cisco': cisco, 
    'bnt': bnt, 
    ... 
} 

choice = vendors[vendor] 
+0

以及如何引用字典内的各个字段? – idan357

+0

我不认为“修复”构建七个单独字典的错误设计决定是一个好主意。 @ BurhanKhalid的解决方案更清洁。 –

0

保持与关键的供应商名称和值作为供应商的字典词典的厂商。值

>> 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" %vendor