0

I have a dictionary:

dictionary_a = {
    "name": "a"
}

and a variable:

dictionary_selection = "dictionary_a"

Is there a way to get elements from the dictionary determined by the variable?

E.g.

Is there some way to get a script like this to work?

print(dictionary_selection["name"])

Not sure if this is possible or if the title is correct

slackmart
  • 4,754
  • 3
  • 25
  • 39
alix
  • 43
  • 5
  • The normal way to select something by name in Python is a dictionary. So you'd have something like `all_dicts = {'dictionary_a': {...}, ...}`, and use `all_dicts[dictionary_selection]["name"]` to retrieve an item from a specified dictionary. – jasonharper Oct 15 '19 at 02:31
  • variable variables dupe https://stackoverflow.com/q/1373164/674039 – wim Oct 15 '19 at 02:32

3 Answers3

1

You may have a try on globals() and locals() functions.

>>> dictionary_a = {"name":"a"}
>>> dictionary_selection = "dictionary_a"
>>> globals().get(dictionary_selection)["name"]
'a'
# locals() use like globals() 

But the better way may be:

data = {}
data["dictionary_a"] = {"name":"a"}
dictionary_selection = "dictionary_a"
data.get(dictionary_selection)["name"]
# this way can control the data by yourself with out the constraint of namespaces

emmm,hope can help you .

lanhao945
  • 427
  • 5
  • 21
-1

It can be done like this.

dictionary_a = {"name": "a"}
dictionary_selection = "dictionary_a"
key="name"
index=eval(dictionary_selection+"["+"'"+key+"'"+"]")
print(index)
-1

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'])
csoham
  • 140
  • 7