create python dictionary with same function but different parameters [duplicate] - python

This question already has an answer here:
Dictionary With Lambda Values Updates All Entries
(1 answer)
Closed 1 year ago.
Hi this puzzeles me for a while now:
I want to add to an existing dictionary a new key with a specific function (myfun) but using different parameters for the same function:
dct = {}
params = {'a':[10,20],'b':[-10,10]}
def myfun(x,y):
return (x+y)
print(myfun(*params['a'])) #desired output for dct['a'](1,1) = 30
print(myfun(*params['b'])) #desired output for dct['b'](1,1) = 0
for key in params.keys():
dct[key]=lambda x,y: myfun(params[key][0]*x,params[key][1]*y)
print(dct['a'](1,1)) # should be 30
print(dct['b'](1,1)) # should be 0
but apparently it keeps only the last key (in this case 'b').
Any ideas?

Thanks #Chris:
use lambda-parameters initialized:
dct[key]=lambda x,y,xx=params[key][0],yy=params[key][1]: myfun(xx*x,yy*y)
this resolved my question!

Related

How to generate a list of object with different names? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Initialize a list of objects in Python
(4 answers)
Closed 11 days ago.
The community is reviewing whether to reopen this question as of 11 days ago.
I have an object called myObject() and want to generate several instances from it and make a list of those instances. The manual way is like this:
object_name_1 = myObject()
object_name_2 = myObject()
Then:
object_name_list = [object_name_1, object_name_2, ...]
My question is how to create such a list with a more automated method? I tried something like this, but it doesn't work
def create_object_name_list(obj, number_of_instances):
object_list = list()
for i in range(number_of_instances):
i = obj
object_list.append(i)
return object_list
object_name_list = create_object_name_list(myObject(), 3)
It returns a list of myObject() itself.
object_name_list
[myObject(),
myObject(),
myObject()]
To add more context as why this question arises. I'm generating a diagram using a module called schemdraw as in the following code, but I think the question can be applied to other similar cases:
with schemdraw.Drawing() as d:
d += (x := Box(w=4).label('x label'))
d += Line().down(d.unit/8).at(x.S)
d += (y := Box(w=4).label('y label'))
d += Line().down(d.unit/8).at(y.S)
d += (z := Box(w=4).label('z label'))
In essence, what that code does is to create a few box shapes as objects x, y, z. These objects can be referred to, for example to indicate where to draw a line, as seen in .at(x.S), which means at the bottom (South) of x. As such their names should be unique.
As you can see, it will get tedious and boring if I need to draw a few dozens of boxes in a repetitive manner. A solution would be to have a list of unique object references (and another list of string labels, such as object_name_label), so it can be made like this:
with schemdraw.Drawing() as d:
for idx, obj in enumerate(object_name_list):
d += (obj := Box(w=4).label('{} label'.format(object_name_label[idx]))
d += Line().down(d.unit/8).at(obj.S)

How to get content of each of the multiple function returns in Python? [duplicate]

This question already has answers here:
Ignore python multiple return value
(12 answers)
Closed 8 months ago.
Suppose we have a function abc where it returns four dicts after some processing as shown. For future if I will only need one tuple from the four, how to get it?
Eg., I only want dict d_two which function abc returns or content of each of the four returns?
def abc():
d_one = dict()
d_two = dict()
d_three = dict()
d_four = dict()
.
.
.
.
return (d_one, d_two, d_three, d_four)
You would need to deconstruct the returned value. There are multiple ways of doing this.
I should also note that dict() doesn't create tuples it creates dictionaries, but the process would be the same for both.
Here are some examples
_, d_two, _, _ = abc()
# or
d_two = abc()[1]
# or
dicts = abc()
d_two = dicts[1]

How to get the value from JSON key and update it accordingly? [duplicate]

This question already has answers here:
Edit the values in a list of dictionaries?
(4 answers)
Closed 1 year ago.
I have the following JSON, I want to be able to get the value for a certain key and update it accordingly.
So for example take a look at the key 'a' in the first JSON object, I want to be able to get its value '2' and then update the value for 'a' to whatever I want. It is important I can work with the value, incase I want to reformat date/time for example and update the key.
All help appreciated
x = "test" : [{
"a":"2",
"b":"12",
"c":"24",
"d":"223",
"e":"23",
},
{"a":"22",
"x":"24",
"c":"25",
"d":"21",
"e":"25",
},
{"a":"12",
"y":"23",
"c":"25",
"d":"23",
"e":"21",
}],
You could do this.
keyFor = 'a'
#get value
aVal = x['test'][0][keyFor]
#change value
aVal = int(aVal) + 2
#substitute in x
x['test'][0][keyFor] = aVal
print(x)

Create Variable Name When Defining A Function [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am working in Python trying to write a function using a list of variables.
Here is the data I am working with:
material_list=['leather', 'canvas', 'nylon']
def materialz(MAT):
MAT=support.loc[(material==MAT)].sum()
for i in enumerate(material_list):
materialz(i)
What I am looking for is to pass in each of the items in the list to the function to produce global variables.
leather=
canvas=
nylon=
Any help would be appreciated!
You could create a dictionary and dynamically assign the key-value pairs there. Such as:
material_list=['leather', 'canvas', 'nylon']
material_dict={}
for i in enumerate(material_list):
material_dict[i]=value #Where i would be the key and value the value in the key-value pair
you can use exec
var = 'hello'
output = hello
exec('var = "world"')
print(var)
output = world

Python incrementally set a variable to equal another variable [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am attempting to set the value of a variable to incrementally equal that of another variable based on the iteration of the loop I am on.
I have the following code:
no_keywords=3
cat_0='Alpha'
cat_1='Bravo'
cat_2='Charlie'
cat_3='Delta'
for _ in range(no_keywords):
keyword1 = exec(f'cat_{_}')
print(keyword1)
However the printed value just returns a NoneType object. I would like the value of Keyword1 to take on the value of the cat_ variable based on the iteration of loop I am on.
Please can somebody help in explaining in what I am doing wrong and help me recitfy?
Thanks,
D
Try this:
no_keywords = 3
cat_0 = 'Alpha'
cat_1 = 'Bravo'
cat_2 = 'Charlie'
cat_3 = 'Delta'
for _ in range(no_keywords):
keyword1 = None
exec(f'keyword1 = cat_{_}')
print(keyword1)
Seems like exec does not return a value, but you can set your variable within the command passed to it.

Categories