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)}
Related
I'm writing a method that takes in a list and returns a dictionary. This method is to be saved in a separate Python file and imported into Main.py
The method that takes in a list calls another method that's meant to update the global dictionary.
global myDict
def addKeyValuePair(listItem):
try:
key = listItem.split(': ')[0].replace('\\','')
value = listItem.split(': ')[1].replace('\\r\\n','').replace('\\','')
myDict.update({key:value})
except:
pass
def makeDict(dataList):
myDict = {}
for listItem in dataList:
addKeyValuePair(listItem)
return(myDict)
From the main method I'm importing the makeDict module and passing it the dataList, but it returns an empty dictionary.
from Toolkit import makeDict
finalDict = makeDict(dataList)
Any idea how this can be done?
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())
I'm trying to dynamically add function calls to fill in array columns. I will be accessing the array millions of times so it needs to be quick.
I'm thinking to add the call of a function into a dictionary by using a string variable
numpy_array[row,column] = dict[key[index containing function call]]
The full scope of the code I'm working with is too large to post here is an equivalent simplistic example I've tried.
def hello(input):
return input
dict1 = {}
#another function returns the name and ID values
name = 'hello'
ID = 0
dict1["hi"] = globals()[name](ID)
print (dict1)
but it literally activates the function when using
globals()[name](ID)
instead of copy pasting hello(0) as a variable into the dictionary.
I'm a bit out of my depth here.
What is the proper way to implement this?
Is there a more efficient way to do this than reading into a dictionary on every call of
numpy_array[row,column] = dict[key[index containing function call]]
as I will be accessing and updating it millions of times.
I don't know if the dictionary is called every time the array is written to or if the location of the column is already saved into cache.
Would appreciate the help.
edit
Ultimately what I'm trying to do is initialize some arrays, dictionaries, and values with a function
def initialize(*args):
create arrays and dictionaries
assign values to global and local variables, arrays, dictionaries
Each time the initialize() function is used it creates a new set of variables (names, values, ect) that direct to a different function with a different set of variables.
I have an numpy array which I want to store information from the function and associated values created from the initialize() function.
So in other words, in the above example hello(0), the name of the function, it's value, and some other things as set up within initialize()
What I'm trying to do is add the function with these settings to the numpy array as a new column before I run the main program.
So as another example. If I was setting up hello() (and hello() was a complex function) and when I used initialize() it might give me a value of 1 for hello(1).
Then if I use initialize again it might give me a value of 2 for hello(2).
If I used it one more time it might give the value 0 for the function goodbye(0).
So in this scenaro let's say I have an array
array[row,0] = stuff()
array[row,1] = things()
array[row,2] = more_stuff()
array[row,3] = more_things()
Now I want it to look like
array[row,0] = stuff()
array[row,1] = things()
array[row,2] = more_stuff()
array[row,3] = more_things()
array[row,4] = hello(1)
array[row,5] = hello(2)
array[row,6] = goodbye(0)
As a third, example.
def function1():
do something
def function2():
do something
def function3():
do something
numpy_array(size)
initialize():
do some stuff
then add function1(23) to the next column in numpy_array
initialize():
do some stuff
then add function2(5) to the next column in numpy_array
initialize():
do some stuff
then add function3(50) to the next column in numpy_array
So as you can see. I need to permanently append new columns to the array and feed the new columns with the function/value as directed by the initialize() function without manual intervention.
So fundamentally I need to figure out how to assign syntax to an array column based upon a string value without activating the syntax on assignment.
edit #2
I guess my explanations weren't clear enough.
Here is another way to look at it.
I'm trying to dynamically assign functions to an additional column in a numpy array based upon the output of a function.
The functions added to the array column will be used to fill the array millions of times with data.
The functions added to the array can be various different function with various different input values and the amount of functions added can vary.
I've tried assigning the functions to a dictionary using exec(), eval(), and globals() but when using these during assignment it just instantly activates the functions instead of assigning them.
numpy_array = np.array((1,5))
def some_function():
do some stuff
return ('other_function(15)')
#somehow add 'other_function(15)' to the array column.
numpy_array([1,6] = other_function(15)
The functions returned by some_function() may or may not exist each time the program is run so the functions added to the array are also dynamic.
I'm not sure this is what the OP is after, but here is a way to make an indirection of functions by name:
def make_fun_dict():
magic = 17
def foo(x):
return x + magic
def bar(x):
return 2 * x + 1
def hello(x):
return x**2
return {k: f for k, f in locals().items() if hasattr(f, '__name__')}
mydict = make_fun_dict()
>>> mydict
{'foo': <function __main__.make_fun_dict.<locals>.foo(x)>,
'bar': <function __main__.make_fun_dict.<locals>.bar(x)>,
'hello': <function __main__.make_fun_dict.<locals>.hello(x)>}
>>> mydict['foo'](0)
17
Example usage:
x = np.arange(5, dtype=int)
names = ['foo', 'bar', 'hello', 'foo', 'hello']
>>> np.array([mydict[name](v) for name, v in zip(names, x)])
array([17, 3, 4, 20, 16])
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 ````
This question already has answers here:
Calling a function of a module by using its name (a string)
(18 answers)
Closed 6 years ago.
I want to select a function based on the value of a dictionary:
dict = {"func_selector":"func1", "param_value":"some_value"}
# defined a function
def func1(param):
# some function code
Now, I want to select the function based on the value of some key, so that it can achieve something like:
# calling a function based on some dict value
dict["func_selector"](dict["param_value"])
The syntax is probably wrong, but I am wondering if it is possible to do that in Python or something similar.
Try storing the value of the function in the dictionary, instead of its name:
def func1(param):
print "func1, param=%r" % (param,)
d = {"func_selector":func1, "param_value": "some value"}
Then you can say:
>>> d['func_selector'](d['param_value'])
func1, param='some value'
The best approach IMO is do it like this
def func1(param):
#code
some_value = ... #The value you need
my_dict = {"func_selector": func1, "param_value": some_value }
And then
my_dict["func_selector"](my_dict["param_value"])
Now, if you only have the name of the function you need to call getattr
And call it
getattr(my_class, my_dict["func_selector"])(my_dict["param_value"])
my_class is the class which contains the method. If it's not in a class I think you can pass self