python passing dictionary parameter with key [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I want to make a function call with a dictionary like:
valueattime(simulaton_01['Temperature_05'], 20)
but I always get a syntax error with the following function
def valueattime(experiment[key], time):
...
It works with simple parameters. But for autocompletion sake it would be great to pass the parameters in the dictionary-form.
Any ideas?

You don't need to change the function signature to pass parameters directly from the dictionary:
def valueattime(temperature, time):
...
valueattime(simulation_01['temp_05'], 20) # this works just fine
Python will first run simulation_01['temp_05'] to retrieve the value, and pass it as temperature to the function.

You should pass it as a regular argument:
def valueattime(temp, time):
pass
a = {'some_key': 'some_value'}
valueattime(a['some_key], 20)
This works!
To supply dictionary items to a function, you can use dictionary comprehension:
new_dict = {k: valueattime(v) for k, v in a.iteritems()}

Remember it'a all objects...
def valueattime(temp, time)
Defines a method taking two input parameters, two object which are referred to by the names temp and time
simulation_01['temp_05'] return an object, so calling your method like: valueattime( simulation_01['temp_05'], 20 ) should be what you are looking for

Related

Does python support iterating through *args argument? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
def my_tup(*args):
for _ in args:
return _
print(my_tup(1,2,3,8,6))
I'm getting 1 as my output
Just as a list, I want to know if I can iterate the *args.
My expected output was (1,2,3,8,6).
The return statement in the body of the loop terminates the successful iteration early.
def my_tup(*args):
for _ in args:
print(_)
my_tup(1,2,3,8,6)
produces
1
2
3
8
6
as output.
It's not clear what my_tup is supposed to do; you could simply write
def my_tup(*args):
return args
because args is already a value of type tuple.
It does support iterating through *args argument. See for yourself. Defining
def f(*args):
for arg in args:
print(arg)
which implies iteration, is assuming, e.g. the following usage
>>> f('a', 'b')
a
b

"SyntaxError: non-keyword arg after keyword arg" when passing arguments into function calls [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Passing an argument-provided value to a defined function seems impossible in my code. What am I doing wrong?
def setParams(params):
retList=[]
for param in params:
retList.append(dict(actualParameterName=param,value=params[param]))
return dict(parameters=dict(actualParameter=retList))
def runProcedure(procedure, project, invalidlyValidArguments):
print(cmdr.httpPost(cmdr.makeEnvelope(
cmdr.createRequest('runProcedure',
dict(procedureName=procedure,
projectName=project,
setParams(params=invalidlyValidArguments)
)))))
#Intended_Purpose=runProcedure(procedure='Build_Single_Module_For_Every_Config',project='My-module',validInvalidArgs={'moduleSelection':'Some_Handler','hakuna':'mattata'})
I expected this to evaluate cleanly, however I get
File "<ipython-input-34-c27d4a9b1a82>", line 19
setParams(params=invalidlyValidArguments)
SyntaxError: non-keyword arg after keyword arg
Even when I set line 19 to setParams(invalidlyValidArguments), that yields the same error.
I failed to realize that my prior call to dict() already required a key-value pair. Python was not, as I assumed upset with my function call, but rather the fact that it could not interpret the output of the setParams into a key/value pair.
setParams(params=invalidlyValidArguments)
does not evaluate to a valid key pair for the underlying dict() call to evaluate.
I need to change
dict(procedureName=procedure,
projectName=project,
setParams(params=invalidlyValidArguments)#this is NOT a valid key-pair
)
To something like
dict(procedureName=procedure,
projectName=project,
parameters=setParams(invalidlyValidArguments)
and have that setparams function remove one of its dictionary envelopes.

What's the correct way to pass by reference [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have seen other people ask a question but the only answers I have seen simply explain that python doesn't have the same concept of pass by reference vs pass by value as languages like C do.
for example
x=[0]
def foo(x):
x[0] += 1
In the past, I have been using this work around but it seems very un-pythonic so I'm wondering if there is a better way to do this.
let's assume for what ever reason returning values won't work, like in the case where this code runs on a separate thread.
Some python objects are immutable (tuple, int, float, str, etc). As you have noted, you cannot modify these in-place.
The best workaround is to not try to fake passing by reference, instead you should assign the result. This is both easier to read and less error prone.
In your case, you could call:
x = 0
def f(x):
return x + 1
x = f(x)
If you truly need to fake passing by reference (and I don't see why you would need that), your solution works just fine, but keep in mind that you do not actually modify the object.
x = 0
x_list = [x]
print(id(x_list[0])) # 1844716176
def f(x_list):
x_list[0] += 1
f(x_list)
print(x) # 0, not modified
print(id(x_list[0])) # 1844716208

Program skipping over if statement in for loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to update a clients details with a function. But it doesn't work. I debug the program and I realized that it never goes into the if. I don't know why?
This is the function:
def UpdateClient(self,id,cnp,name,adress):
for i in range (len(self.clients.get_all())):
if self.clients.get_all()[i].get_id==id:
self.clients.get_all()[i].set_name(name)
self.clients.get_all()[i].set_cnp(cnp)
self.clients.get_all()[i].set_adress(adress)
When I try to update the client, I give the id, name, cnp, and adress, but when I print the list nothing is changed. I cannot go into the if with the debugger because it said that they are never equal. Why?
Note that get_id is not the same as get_id(). The former references the method, while the latter actually calls it.
In addition, consider simplifying your code by writing more idiomatic Python. For example:
for client in self.clients.get_all():
if client.get_id() == id:
client.set_name(name)
...
The issue here is you are making your check as get_id == id but it is a function. Your if should be like:
if self.clients.get_all()[i].get_id()==id:
# ^ making it a function call
Also, better way to do this is by storing self.clients.get_all() in a separate variable. Hence, your code should look like:
def UpdateClient(self,id,cnp,name,adress):
clients = self.clients.get_all()
for i in range (len(clients)):
if clients[i].get_id()==id:
clients[i].set_name(name)
clients[i].set_cnp(cnp)
clients[i].set_adress(adress)

Python __dir__() doesn't change dir() [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I want to add 'dir' method to my object so when dir() is called on it, my function will be called.
My code looks like this:
class c(object):
def __dir__(self):
return ["a"]
print dir(c())
print c().__dir__()
Only the second print shows ["a"], and the first acts like normal.
I've tried this in several ways and sometimes it works and sometimes it doesn't. Any ideas why?
Edit:
I was missleading, my code is more complex then I showed. To be exact, my code creates an object 'x' with dir method and writing:
x.__dir__()
Works, but
x.__dir__() == dir(x)
Returns false
I suspect you are writing dir(c) instead of dir(c()) somewhere. The difference is calling dir on a class (dir(c)) invokes the class object which itself has a default __dir__(), which will give the undesired default behavior. What you have in your question right now (dir(c())) should work.

Categories

Resources