pass kwargs and default values to ordered list - python-2.7

Using python 2.7, I have been researching into using keyword arguments to pass a function that inserts a new tuple into a list.
My goal: have a function that takes one required argument, and n number of arguments that then get inserted into a tuple at specific positions and have a default value if nothing was passed.
Here is what I have so far:
def add_tagging_log_row(key, **time_stamp):
tagging_log_rows.insert(len(tagging_log_rows), (key, time_stamp.get('is_processed'), time_stamp.get('is_processed')))
add_tagging_log_row('zzz', is_processed=datetime.datetime.now(), is_audited=datetime.datetime.now())
Here is a sample of tagging_low_rows list I am building with all values in the tuple populated:
[('key1', datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now()), ('key2', datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now())]
here is the order of the items in each tuple in the list:
key | is_processed | is_archived | is_error | is_audited
The problem is when calling the function add_tagging_log_row(), I will always pass a 'key' but might or might not pass the other timestamp fields to the tuple when it is inserted into the list. I need these fields to be empty strings ('').
Is using **kwargs the right way to approach this problem?

Yes, using kwargs works. You would need some exception handling inside your function though. kwargs passed in as a dictionary. You can check if a given timestamp exists in the dictionary and use an empty string if it doesn't. Try doing something like this inside the function:
timestamps_order = ['is_processed', 'is_archived', 'is_error', 'is_audited']
required_tuple = tuple([key] + [time_stamp[k] if k in time_stamp else "" for k in timestamps_order])
On a side note - please consider switching to Python 3. Python 2.7 is at the end of life and won't receive any future support. Most libraries have stopped supporting it.

Related

How to iterate and store variables in a dictionary?

I am new to python and my coding experience so far is with MATLAB.
I am trying to understand more about lists and dictionaries as i am using a library about DOEs that takes an dictionary as a passing argument.
But my trouble so far is that this dictionary assumes the form of ex.
DOE={'Elastic Modulus':[10,20,30], 'Density':[1,2,3], 'Thickness':[2,3,5]}
But i need this dictionary to be user defined, for example:
Have an input to define how many variables are needed (in this example are 3: Elastic Modulus','Density'and 'Thickness)
as the variables are defined, it should be able to store values in the dictionary over a for loop.
Is this possible using dictionaries?
Or is it better to use a list and convert in a dicionary later?
Thank you in advance
One can add keys and the corresponding values to a dict one at a time like so:
my_dict = {}
num_entries = int(input("How many entries "))
for _ in range(num_entries):
key = input("Enter the key: ")
value = input("Enter the value: ")
my_dict[key] = value
Presumably you would have a loop to do the entry of key and value for the number of values you wish to enter. Also if you are in python 2 it needs to be raw_input rather than input function. [Edit: Showing how to do the loop, since I noticed that was part of your question]

Convert a single list item of key value pair to an dictionary in python

I have function that returns just one list of key-value pair. How can I convert this to an actual key value or an object type so I can get each attribute from the list. For example I would like to be able to just get the time or price or any other property and not the whole list as one item.
{'time': 1512858529643, 'price': '0.00524096', 'origQty': '530.00000000'
I know it doesn't look like a list but it actually is! The function that I am calling returns this as a list. I am simply storing it to a variable and nothign else.
open_order=client.get_open_orders(symbol="BNBETH",recvWindow=1234567)
If you still have doubts. When I try to print a dictionary item like this print(open_order['time'])
I get the following error.
Traceback (most recent call last):
File "C:\Python27\python-binance-master\main.py", line 63, in <module>
print(open_order['time'])
TypeError: list indices must be integers, not str
Also If I show type it shows as list.
print(type(open_order))
So, I was able to come up with a solution, sort of... by converting the list to string and splitting at the "," character. Now I have list of items that I can actually print by selecting one print(split_order_items[5]) There has to be a better solution.
open_order=client.get_open_orders(symbol="BNBETH",recvWindow=1234567)
y=''.join(str(e)for e in open_order)
split_order_items =([x.strip() for x in y.split(',')])
print(split_order_items[5])
I was able to create a multiple list items using the above code. I just can't seem to convert it to dictionary object!
Thanks!
What you have posted is a dict, not a list. You can do something like this:
data = {'time': 1512858529643, 'price': '0.00524096', 'orderId': 7848174, 'origQty': '530.00000000'}
print(data['time']) # this gets just the time and prints it
print(data['price']) # this gets just the price and prints it
I strongly suggest reading up on the Python dict: https://docs.python.org/3/tutorial/datastructures.html#dictionaries

Adding and removing elements from a set Pyomo

I wan't to create a free Set that will be initialized through a mutable parameter that is changed throughout my program.I wan't the set to contain only one value the value of the parameter each time is changed,but i can't add and remove the values from the set.If it was a list it could be done like so:
model.iter=RangeSet(0,1000)
model.ir=[]
model.count1=Param(mutable=True)
def solve_function(model,instance):
instance=model.create_instance()
for i in instance.iter:
if i==value(instance.count):
instance.ir.append(i)
else:
pass
results= opt.solve(instance)
instance.solutions.load_from(results)
.#some code
.
.
.
instance.ir=[]
Can anybody tell me how to do the same thing with a Set() object?

grails controller: access to parameter that has a list of elements

I need to access to items stored in a parameter that represents selected elements in a multiselect. I pass selected items from gsp to controller with the following code into the remoteFunction:
params: '\'receiptItemsSelected=\' + jQuery(this).val()'
Now, following the code found in discussion here, I use the closure to get each value, but if I perform a multiselect, the size of receiptItemsSelected is always 1, but value is, for example, 1,2. To get values as a list I've done the following in the controller
params.list("receiptItemsSelected")
but it does not give me two elements if I select two items in the multiselect, but always one element.
The question is: if I select two elements, how can I get each element and use it in the controller? And how can I have that elemnts as Long and not as String?
Thanks
If you're parameters are being passed with string representation of a list, e.g.:
http://yoursite.com/?receiptItemsSelected=1,2,3
You have to split the value using normal Groovy string manipulation and perform the type conversion yourself:
def receiptsAsLongs = params.receiptItemsSelected.split(',')*.toLong()
If your parameters are passed with the convention of repeated parameters makes a list, e.g.:
http://yoursite.com/?receiptItemsSelected=1&receiptItemsSelected=2
Then grails can convert this to a list for you using params.list(), but you must do the final String to Long conversion:
def receiptsAsLongs = params.list('receiptItemsSelected')*.toLong()
params.list() is intended for multi-valued parameters, i.e. it will work if you have
receiptItemsSelected=1&receiptItemsSelected=2
You may have more luck using serialize() rather than val() to build the request body.

Using integer as dictionary key using dict()

I'm trying to use numbers as my dict key. Is there anyway to initiate the dictionary using dict() method?
This works
mydict = { '100':'hundred', '200':'two hundred'}
This doesn't work?
mydict = dict( 100='hundred' )
The error says 'keyword can't be an expression' and I couldn't find any solution.
Thank you.
I can't understand your question exactly, but you mentioned to use number as dict key right? you just directly initiate it using integer instead string like this..
a = {1:'one',100:'hundered'}
print a
{1: 'one', 100: 'hundrered'}
No, it mist be a valid python identifier, so it cannot start with a number.
You can read where i found it at here in the part about dict
https://docs.python.org/2/library/stdtypes.html#typesmapping
Like the comment above says you can use an int, since dictionaries just hash the string and you get an int anyways, in the case of an int it just hashes to itself. But it doesnt work with dict ()
On that page it shows you can do
mydict = dict (zip ([1], ["one"]))
Which is kinda ugly imo, but seems to get the job done
To use the dict method you need to feed it a list or tuple of lists or tuples.
>>> dict([(100, 'hundred'), (200, 'two hundred')])
{200: 'two hundred', 100: 'hundred'}