简体   繁体   中英

Call dictionary from variable python

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?

Eg

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

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.

It's a bit hacky but it should work

>>> import sys
>>> thismodule = sys.modules[__name__]
>>> dictionary_a = {"name": "a"}
>>> dictionary_selection = "dictionary_a"
>>> name = getattr(thismodule, dictionary_selection)['name']
>>> print(name)

Here I'm using the getattr built-in function, and it basically takes a object (where you want to get an attribute from) and the attribute name string.

__name__ is an special variable set to the current module name, in this case its value is '__main__' , and given that the dictionary_a is defined in the current interactive shell, it works.

You could also try with a class:

class A:
    dictionary_a = {"name": "a"}


dictionary_selection = "dictionary_a"
name = getattr(A, dictionary_selection)['name']

It can be done like this.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM