Dear all,
I’m trying to understand if it possible to do something as below. I have a list with name:
list=["Mercury","Venus","Sun"]
and I have the following dictionary
d_Mercury={}
d_Venus={}
d_Sun={}
is it possible to do something call the dictionary dynamically based on the value of the list considering the dictionary name have all same name patter: d_list[i]
in other words something like
for i in list
d_list(i)[key]=value #this shoud result by instance in something like d_Mercury{key}=value
I hope my explanation had been clear enough otherwise please let me
Hi there and thanks for you input! @Jagaya : the only references I found were about locals() and Globals() kind of ‘variables’ used in python and nothing about using a string as name of a dictionary.
Below there is a simple example of code I’m using developing (it is just an easy example):
d_mercurio={}
d_venus={}
planets=["mercurio","venus"]
while a <=10
....some calculation
if a ==0:
d_mercurio[key]=value
elif a==1:
d_venus[key]=value
a +=1
because I have several calculations I’d like to remove the use of if-elif to reduce the calculation load towards something like:
while a <=10
some calculation
dictionary_name={"d_"+planets[a]}# my aim is this passage should return something like d_mercurio if a=0 etc
dictionary_name[key] = value #use the dictionary_name string now not like a string but like name of a dictionary
a +=1
I can for sure reduce the amount of typing with a function which does the if-elif loops but won’t recude the calculation load.
The following link goes into several methods of how to turn a string into a variable (which then ofcourse can be a dictionairy) - the second one is using locals()
Ok…I gave a look and do some tryies and I’m still getting trouble to get it working.
this is a quick script which returns error
pianeta=["mercurio","venere"]
d_mercurio={}
d_venere={}
d_mercurio= {"b":2}
str ={"d_"+pianeta[0]}
print (str)
globals()[str]={"a":2} #append a set key:value to the dictionary with globals() and locals()
print(d_mercurio)
error: unhashable type: ‘set’
Is it possible it only works for variable and not for dictionarys?
That’s not a string, but a set (a special data-structure).
Python saves variables as keys in a dictionairy (which you access by locals() ), so it must be a valid datatype for a key.
Meaning it has to be without the curly-braces: string ="d_"+pianeta[0]
Edit:
str is a Python keyword referring to String-Objects. Those should never be used as variables, as this can cause various errors down the line.
For example I tested your code in a notebook and after that I could no longer cast integer to string, because I’ve overwritten the cast command str with the string “d_mercury”. Had to restart the notebook to undo that.