This question already has answers here:
Call a function with argument list in python
(6 answers)
Closed 9 years ago.
I am trying to write a python script that runs a bunch a function that are specified as a dictionary in JSON (this is user input). Here is what the JSON file contains:
{
"tests_to_run": {"find_holes": [],
"is_greater": [1.2]
}
}
find_holes and is_greater are two functions that I have written, the first taking 0, the second 1 parameter. The idea is to specify these parameters in the list associated with the function key in the JSON dictionary.
I am currently using this dictionary as follows:
functions_dict = {"find_holes": val.find_holes,
"is_monotonic": val.is_monotonic}
def run_functions(dict_tests_to_run):
for func, params in dict_tests_to_run.iteritems():
if params==[]:
functions_dict[func](time_series)
if len(params)==1:
functions_dict[func](time_series, params[0])
It seems a bit awkward to manually check for the length of the parameters, in particular since I am going to have to extend the loop to accomodate functions with up to at least 4 parameters. Is there any better way of doing this?
Thanks,
Anne
You can use the * operator to expand your list into function parameters. For example,
f(1,2,3)
is equivalent to:
a=[1,2,3]
f(*a)
Related
This question already has answers here:
Why dict.get(key) instead of dict[key]?
(14 answers)
Closed 3 years ago.
monthConversions={
"Jan":"January", #key:value
"Feb":'February', #make sure keys are unique
'Mar':'March', #can also use integers
'Apr':"April",
'May':'May',
'Jun':'June',
}
print(monthConversions['Jan']) #gives value associated with the key
print(monthConversions.get('Luv','not a valid key'))
Hi, I am currently learning python through freebootcamp on youtube, and the person mentioned we can use the get function to pass in a value for a key that is not in the dictionary. I kind of understand that, but I fail to see what the use of this would be. I thought it would add Luv in when I put in
print(monthConversions['Luv'])
but it instead gives a error. What would be the purpose of the get function in this situation anyway? It feels like extra work and I don't get how it would be useful. Any explanations would be greatly appreciated, thank you.
It does not change the dict. The second argument is simply what get() returns when key is not found. If you don't specify it, it will simply return None.
This question already has answers here:
How do I create variable variables?
(17 answers)
How can I create multiple variables from a list of strings? [duplicate]
(2 answers)
generating variable names on fly in python [duplicate]
(6 answers)
Closed 3 years ago.
I have a ticker and I want to check a specific list of tickers to see if the ticker is found. If it is found, it will replace it.
The new tickers come from another data source and therefore do not know which specific list of tickers to check. In order to find that list, I can pass the lists name as a string but upon iterating the code (naturally) recognizes this as string as opposed to a list to iterate.
Is there a way to have the code/function recognize that the string is actually a specific list to be checked? In reading other questions, I know this may not be possible...in that case what is an alternative?
list_1=['A','B']
list_2=['C','D']
old_ticker='A'
new_ticker='E'
assigned_list='list_1'
def replace_ticker(old_ticker,new_ticker,list):
for ticker in list:
if new_ticker in list:
return
else:
list.append(new_ticker)
list.remove(old_ticker)
replace_ticker(old_ticker,new_ticker,assigned_list)
You key the needed lists by name in a dictionary:
ticker_directory = {
"list_1": list_1,
"list_2": list_2
}
Now you can accept the name and get the desired list as ticker_directory[assigned_list].
list_1=['A','B']
list_2=['C','D']
lists = {
'list_1':list_1,
'list_2':list_2
}
old_ticker='A'
new_ticker='E'
assigned_list='list_1'
def replace_ticker(old_ticker,new_ticker,list_name):
if old_ticker not in lists[list_name]:
return
else:
lists[list_name].append(new_ticker)
lists[list_name].remove(old_ticker)
replace_ticker(old_ticker,new_ticker,assigned_list)
print(lists[assigned_list])
This is the complete program from what i perceived.
#prune already answered this, I have just given the whole solution
There are at least two possibilities:
1 As noted in comments kind of overkill but possible:
Use eval() to evaluate string as python expressions more in the link:
https://thepythonguru.com/python-builtin-functions/eval/
For example:
list_name = 'list_1'
eval('{}.append(new_ticker)'.format(list_name))
2 Second
Using locals() a dictionary of locally scoped variables similiar to the other answers but without the need of creating the dict by hand which also requires the knowledge of all variables names.
list_name = 'list_1'
locals()[list_name].append(new_ticker)
This question already has answers here:
Why can't Python parse this JSON data? [closed]
(3 answers)
Closed 5 years ago.
I am looking for more info regarding this issue I have. So far I have checked the JSON encoding/decoding but it was not precisely what I was looking for.
I am looking for some way to strip this kind of list quite easily:
//response
{
"age":[
{"#":"1","age":10},
{"#":"2","age":12},
{"#":"3","age":16},
{"#":"4","age":3}
],
"age2":[
{"#":"1","age":10},
{"#":"2","age":12},
{"#":"3","age":16},
{"#":"4","age":3}
],
"days_month":31,
"year":2017
}
So how do I easily extract the data? i.e. I want to get the result age of person in age2 with # == 3.
To get the results for year/days_months I found the solution with google:
j=json.loads(r.content)
print(j['year'])
to retrieve the data. Probably I have missed something somewhere on the internet, but I could not find the specific solution for this case.
I think this is what #Jean-François Fabre tried to indicate:
import json
response = """
{
"age":[
{"#":"1","age":10},
{"#":"2","age":12},
{"#":"3","age":16},
{"#":"4","age":3}
],
"age2":[
{"#":"1","age":10},
{"#":"2","age":12},
{"#":"3","age":16},
{"#":"4","age":3}
],
"days_month":31,
"year":2017
}
"""
j = json.loads(response)
# note that the [2] means the third element in the "age2" list-of-dicts
print(j['age2'][2]['#']) # -> 3
print(j['age2'][2]['age']) # -> 16
json.loads() converts a string in JSON format into a Python object. In particular it converts JSON objects into Python dictionaries and JSON lists into Python list objects. This means you can access the contents of the result stored in the variable j in this case, just like you would if it was a native mixture of one or more of those types of Python datatypes (and would look very similar to what is shown in the response).
As the search criterion you are looking for is not contained in the indices of the respective datastructures, I would do it using a list comprehension. For your example, this would be
[person['age'] for person in j['age2'] if person['#'] == u'3'][0]
This iterates through all the items in the list under 'age2', and puts all the items where the number is '3' into a list. The [0] selects the first entry of the list.
However, this is very inefficient. If you have large datasets, you might want to have a look at pandas:
df = pandas.DataFrame(j['age2'])
df[df['#'] == '3']['age']
which is much more performant as long as your data can be represented by a sort of series or table.
This question already has answers here:
Python Argument Binders
(7 answers)
Closed 8 months ago.
As you can see from the code below, I'm adding a series of functions to a list.
The result is that each function gets ran and the returned value is added to the list.
foo_list = []
foo_list.append(bar.func1(100))
foo_list.append(bar.func2([7,7,7,9]))
foo_list.append(bar.func3(r'C:\Users\user\desktop\output'))
What I would like to know is, is it possible to have the function stored in the list and then ran when it is iterated upon in a for loop?
Yeah just use lambda:
foo_list = []
foo_list.append(lambda: bar.func1(100))
foo_list.append(lambda: bar.func2([7,7,7,9]))
foo_list.append(lambda: bar.func3(r'C:\Users\user\desktop\output'))
for foo in foo_list:
print(foo())
This question already has answers here:
Is there a difference between using a dict literal and a dict constructor?
(12 answers)
Closed 7 years ago.
Consider these two statements, which serve the same purpose:
tel = {'sape': 4139, 'jack': 4098}
and
tel = dict([('sape', 4139), ('jack', 4098)])
Why use "dict()" at all?
I am sure there is a reason, i just want to know it.
The reason for the existence of dict(...) is that all classes need to have a constructor. Furthermore, it may be helpful if the constructor is able to take in data in a different format.
In your example use case, there is no benefit in using dict, because you can control the format the data is in. But consider if you have the data already as pairs in a list, the dict constructor may be useful. This can happen e.g. when reading lines from a file.
map(dict,[[(1,2)]])
[{1: 2}]
map({},[[(1,2)]])
TypeError: 'dict' object is not callable