如何根据用户的选择选择字典?

时间:2014-05-25 07:40:23

标签: python dictionary

我想使用用户输入来引用字典,以便用户选择要使用的字典。

例如,给定词典

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"])

我想使用“cisco”,“bnt”,“ods”等作为索引而不使用if语句。

谢谢!

3 个答案:

答案 0 :(得分:3)

将它们全部放在一个更大的字典中。

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

choice = vendors[vendor]

答案 1 :(得分: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))

答案 2 :(得分: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