所以我有一些词典:
dict1 = { "a": 5, "b": 1, "c": 8 }
dict2 = { "a": 2, "b": 6, "c": 11 }
如何在词典中输入和搜索,无论输入是什么?所以我接受输入并打印该字典的值c
。
这个想法是出于这样的方式:
>>> my_function()
Enter a dict: dict1
The answer is: 8
>>> my_function()
Enter a dict: dict2
The answer is: 11
答案 0 :(得分:6)
你应该这样做:
global_dict = {
'dict_1': {"a":5, "b":1, "c":8},
'dict_2': {"a":2, "b":6, "c":11},
}
dict_name = raw_input("Enter a dict: ")
try:
print(global_dict[dict_name]['c'])
except KeyError:
print('Dict not found')
答案 1 :(得分:0)
正如评论和其他答案所述,建议将这些词汇放在另一个词典中。但是,要实现您想要的功能,您可以使用globals()
功能:
dict_name = raw_input("Enter dict name:")
selected_dict = globals()[dict_name]
print selected_dict['c']
答案 2 :(得分:0)
将它们存储为dicts的词典:
all_dicts = {"dict1":{"a": 5, "b": 1, "c": 8},"dict2":{"a": 2, "b": 6, "c": 11}}
d, v = raw_input("Enter dict and key separated by a space").split()
print(all_dicts.get(d,{}).get(v,"Incorrect dict or key"))