This is what I have
TEST_KEY = "test_key"
def get_dict():
return dict(TEST_KEY = "test_value")
print(get_dict())
This will print out {'TEST_KEY': 'test_value'}
but I want it evaluate to {'test_key': 'test_value'}
Is there a way to achieve this, to have python not evaluate TEST_KEY inside the dict function as a literal String but instead as the variable defined earlier?
Very close! But the way you're assigning the key and value is not quite right.
Try changing dict to {} and = to : like below. This will use the variable value as the key.
TEST_KEY = "test_key"
def get_dict():
return {TEST_KEY: "test_value"}
print(get_dict())
Related
How convert string to a Python object?
I have for example simple function:
def test_function(name):
str(name) + "insert(1, "test_01")
...
test_function("list1")
I want this to perform "list1.insert(1, "test_01) operation but it doesn't work. I guees there is a problem that it reads name as a string not as an object. How can I solve this out?
locals()"YourFunction"
or
globals()["YourFunction"]()
as an example:
def foo(number):
return number*10
print (globals()["foo"](10))
Output= 100
Thanks
I don't know if it's what you really want. But i think it's because of the quotation mark. See below:
def test_function(name):
print(str(name) + 'insert(1, "test_01")')
...
test_function("list1")
NOTE
By any means don't use eval, it is insecure ("eval is evil").
For more details about eval harmfulness read here.
Solution Requested
Using eval you can evaluate string that contains code and execute it.
The code here that is being evaluated, looks for the variable name in the global scope (outside the function).
The globals() dictionary contains the variables defined outside the function.
def test_function(name):
eval(f'(globals()["{name}"]).insert(1, "test_01")')
name = "list1"
list1 = []
test_function(name)
# Outside function
# eval(str(name) + '.insert(1, "test_01")')
print(list1)
So, I was wondering if creating a function with variables that are changing names (but only partially) is possible. Here is an example:
def function(string):
{string} + something = 1
return {string} + something
So when I call it like:
function(test)
it returns variable called "testsomething" that equals 1.
Hope my question is understandable, is this even possible?
It is possible, if you put the variable inside a dictionary:
def function(name):
mydict = {}
mydict[name+"something"] = 1
return mydict
for variables 'a' and 'b' in dictionary 'dict1' is it possible to later call variable 'a' using its key given in 'dict1' to assign a value to it??
a=""
b=""
dict1= {0:a,1:b}
dict1[0] = "Hai" #assign a value to the variable using the key
print(a) #later call the variable```
No, when you do the assignment {key:value}, the value doesn't refer to the original variable, so mutating either one will not affect the other.
The variable is not set automatically, what you could do is:
def update_dic(a,b):
dict1={0:a, 1:b}
return dict1
def update_vars(dict1):
return dict1[0],dict1[1]
Every time you call the first function your dictionary is getting updated, and for the second time you always get a and b back.
You could do something similar using a class to store your variables and the indexing dictionary:
class Variables():
def __init__(self):
self.varIndex = dict()
def __getitem__(self,index):
return self.__dict__[self.varIndex[index]]
def __setitem__(self,index,value):
self.__dict__[self.varIndex[index]] = value
variables = Variables()
variables.a = 3
variables.b = 4
variables.varIndex = {0:"a",1:"b"}
variables[0] = 8
print(variables.a) # 8
We can do this by using two dictionaries with the same amount of variables:
This allows to access the variable 'a' using the key '0' and then altering its value using 'dict2' and later get the value by calling 'a'.
however remember that the variables need to written as string i.e. in quotes, it doesn't work when used as a regular variable.
dict1= {0:'a',1:'b'}
dict2={'a':'x','b':'y'}
dict2[dict1[0]]="Hai" #assign a value to the variable using the key
print(dict2['a']) #later call the variable ````
Let me start by saying I completely agree that you should
keep data out of your variable names
but let's pretend you wanted a function like this:
def setglobal(s, x):
# Some kind of eval or exec trick like eval(s+' = '+x) so we end up
# with a global variable whose name is the string s and that has a value of x.
Does it have to be an exec/eval trick?
def setglobal(s, x):
globals()[s] = x
This seems to work:
# Take a symbol name s as a string and a value x and eval(s+' = '+x) to set a
# global variable with name s to value x. For getglobal(s) use eval(s).
def setglobal(s, x):
exec "global "+s+"; "+s+" = "+repr(x) in globals()
If I have a dictionary from another function, how can I pass the dictionary within a new function?
Eg.
From another function, I have tuples like this ('falseName', 'realName', positionOfMistake), eg. ('Milter', 'Miller', 4). I have a function that make a dictionary like this:
D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...},
realName:{falseName:[positionOfMistake]...}...}
def addNameToDictionary(d, tup):
if not d.has_key(tup[0]):
d[tup[0]] = {}
d[tup[0]][tup[1]] = [tup[2]]
Now I need to write a function that takes a list of falseName's and return:
realName:
falseName
falseName
realName:...
My problem is how to call the dictionary from the function addNameToDictionary, to a new function?
I have tried the following:
def Names(nameList):
D=addNameToDictionary(d, tup)
print D
But I get:
NameError: global name 'd' is not defined
Anyone?
def your_new_function(d, falseNames):
# ... get data from d
return {realname:(falseName1, falseName2)}