Python function argument list from a dictionary - python

I'm still relatively new to Python, and sometimes something that should be relatively simple escapes me.
I'm storing the results of a POST operation to a database table as a character string formatted as a dictionary definition. I'm then taking that value and using eval() to convert it to an actual dict object, which is working great as it preserves the data types (dates, datetimes, integers, floats, strings etc.) of the dictionary data elements.
What has me flummoxed is using the resulting dictionary to construct a set of keyword arguments that can then be passed to a function or method. So far, I haven't been able to make this work, let alone figure out what the best/most Pythonic way to approach this. The dictionary makes it easy to iterate over the dictionary elements and identify key/value pairs but I'm stuck at that point not knowing how to use these pairs as a set of keyword arguments in the function or method call.
Thanks!

I think you're just looking for func(**the_dict)?
Understanding kwargs in Python

You are looking for **kwargs. It unpacks a dictionary into keyword arguments, just like you want. In the function call, just use this:
some_func(**my_dict)
Where my_dict is the dictionary you mentioned.

#tzaman and #Alex_Thornton - thanks - your answers led me to the solution, but your answers weren't clear re the use of the **kwargs in the function call, not the function definition. It took me a while to figure that out. I had only seen **kwargs used in the function/method definition before, so this usage was new to me. The link that #tzaman included triggered the "aha" moment.
Here is the code that implements the solution:
def do_it(model=None, mfg_date=None, mileage=0):
# Proceed with whatever you need to do with the
# arguments
print('Model: {} Mfg date: {} Mileage: {}'.format(model, mfg_date, mileage)
dict_string = ("{'model':'Mustang,"
"'mfg_date':datetime.datetime.date(2012, 11, 24),"
"'mileage':23824}")
dict_arg = eval(dict_string)
do_it(**dict_arg) # <---Here is where the **kwargs goes - IN THE CALL

Related

why can the agg..method use dictionaries with reversed syntax?

This is my first Python-related question so bear with me....
I'm doing the "data scientist with Python"-course at Datacamp. One of the current rows of code I'm supposed to complete looks like this:
print(____.groupby(____).agg({'income':'median'}))
And I guess this bothers me. This is "not" how that method is supposed to work according to the documenation. Although it states dictionaries with arguments on the form "function:variable" can be passed as arguments (though annoyingly enough we have to infer this from the examples) it also states that the function must be the first argument and the variable the second. Why can the order be reversed in the above example?
Is the sequence of functions/columns in dictionaries passed as arguments totally arbitrary?
the correct syntax is:
df.groupby('column_name').agg({"column_name": agg_func})

How to parse the elements of a list as arguments for a method? Specifically, for Google Ads API

I'm trying to modularize a type of report from the API. This is my query for the request:
content = ['CampaignId', 'AdvertisingChannelType', ...]
report_query = (adwords.ReportQueryBuilder()
.Select(content)
.From('CAMPAIGN_PERFORMANCE_REPORT')
.During(start_date=since,end_date=until)
.Build())
However, I'm having a problem with the .Select() statement since its common usage is .Select('CampaignId', 'AdvertisingChannelType', ...) (as the list but without the brackets []) and in my query I'm parsing the arguments as a list, which of course returns an error.
My question is, how can I parse the elements of content as required? I've tried turning the list into a string but it doesn't work as all the list becomes a single element. I can't assign by hand the elements since it's number may vary (will be used for more than one client).
Any help will be appreciated. Thanks!
I'm not sure exactly if this is helpful, but maybe try looking into python maps.

What is the Python equivalent for the R function names( )?

The function names() in R gets or sets the names of an object. What is the Python equivalent to this function, including import?
Usage:
names(x)
names(x) <- value
Arguments:
(x) an R object.
(value) a character vector of up to the same length as x, or NULL.
Details:
Names() is a generic accessor function, and names<- is a generic replacement function. The default methods get and set the "names" attribute of a vector (including a list) or pairlist.
Continue R Documentation on Names( )
In Python (pandas) we have .columns function which is equivalent to names() function in R:
Ex:
# Import pandas package
import pandas as pd
# making data frame
data = pd.read_csv("Filename.csv")
# Extract column names
list(data.columns)
not sure if there is anything directly equivalent, especially for getting names. some objects, like dicts, provide .keys() method that allows getting things out
sort of relevant are the getattr and setattr primitives, but it's pretty rare to use these in production code
I was going to talk about Pandas, but I see user2357112 has just pointed that out already!
There is no equivalent. The concept does not exist in Python. Some specific types have roughly analogous concepts, like the index of a Pandas Series, but arbitrary Python sequence types don't have names for their elements.

How to set value in python dictionary while looking it up from another dictionary?

I have two dictionaries. The first is mapping_dictionary, it has several key-value pairs. It will serve as a reference. The second dictionary only has two key-value pairs. I would like to look up the value that should be assigned to the second dictionary in the mapping_dictionary and set it to one of the values. I tried doing it a few different ways but no success.
Please let me know if the syntax is wrong or if this is not the way to do something like this in Python? Thank you in advance for any help.
Example 1:
mapping_dictionary={'TK_VAR_DEC':1, 'TK_ID':2, 'TK_COMMA':3}
token_dictionary={'TK_TYPE', 'TK_VALUE'}
tk_v=mapping_dictionary.get("TK_VAR_DEC")
token_dictionary['TK_TYPE']=tk_v
token_dictionary['TK_VALUE']="VAR_DEC"
Example 2:
token_dictionary['TK_TYPE']=mapping_dictionary.get("TK_VAR_DEC")
token_dictionary['TK_VALUE']="VAR_DEC"
With the definition of the token_dictionary, you're not defining a dictionary at all -- you've written the literal syntax for a set. You need to specify values for it to be a dictionary. I expect that if you change to using token_dictionary = {'TK_TYPE': None, 'TK_VALUE': None} you'll have more luck.
Also note that using .get() is unnecessary for retrieving a value from the dictionary. Just use [].

Multiple assignments from a python dictionary

Is it possible to make this line of code valid?
description, content, state, city, datetime = makeTupleRightOrder(dictionary)
this makeTupleRightOrder would get the 'parameters' from the left side of the assignment, convert their names to strings and build a list getting their values from the dictionary.
No. The function has no idea what's on the left side of the assignment, and even if it did, the variables might well have names different from the keys.
kindall is right. For the general case, you can't do this. What you can do is sort the keys alphabetically, and always make sure that the variables you are unpacking the dict to are in the correct (alphabetic order) in terms of the keys:
city, content, datetime, description, state = [dictionary[k] for k in sorted(dictionary)]
(This example assumes the dictionary keys are named identically to the variables you are unpacking them to).
NOTE
If you are running into situations where you are forced to do this, I would consider designing your code differently. Your implementation is probably flawed.

Categories