2014-05-25 35 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