Reputation: 123
So I have some dictionaries:
dict1 = { "a": 5, "b": 1, "c": 8 }
dict2 = { "a": 2, "b": 6, "c": 11 }
How do I take input and search in the dictionary called whatever the input is? So I take input and print the value c
of that dictionary.
The idea is for something that acts this way:
>>> my_function()
Enter a dict: dict1
The answer is: 8
>>> my_function()
Enter a dict: dict2
The answer is: 11
Upvotes: 0
Views: 85
Reputation: 180411
Store them as a dict of 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"))
Upvotes: 0
Reputation: 13376
As said in comments and other answers, it's recommended to put the dicts inside another dict. However to achieve what you want you can use the globals()
function:
dict_name = raw_input("Enter dict name:")
selected_dict = globals()[dict_name]
print selected_dict['c']
Upvotes: 0
Reputation: 23068
You should do that instead:
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')
Upvotes: 6