Say you have a dictionary d
d={'apple': 'fruit', 'onion':'vegetable'}
Trying to do the following will give you an error:
dict_name='d'
print(d['apple'])
This is because dict_name
stores a string
with value d
. Even though d
is the name of a variable, python does not know to evaluate it as such and you will get an error like
TypeError: string indices must be integers
You could evaluate the string by doing this:
eval(dict_name)['apple']
This will evaluate the variable, see that it is a dictionary, and give you the output apple
.
However, this is not a good way to do it. You would be better off using another dictionary or list to keep track of all your dictionaries.
with list:
dict_list=[d, d1, ...]
print(dict_list[0]['apple'])
with dictionary:
all_dicts{'d':d}
print(all_dicts['d']['apple'])