Passing a Dictionary to a Function as Keyword Parameters

Passing a dictionary to a function as keyword parameters

Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

So my example becomes:

d = dict(p1=1, p2=2)
def f2(p1,p2):
print p1, p2
f2(**d)

How to pass a Dict to a function with Keyword arguments?

Dictionaries with Symbol keys can be directly splatted into the function call:

julia> d = Dict(:arg1 => 10, :arg2 => 12)
Dict{Symbol, Int64} with 2 entries:
:arg1 => 10
:arg2 => 12

julia> f(; arg1, arg2) = arg1 + arg2
f (generic function with 1 method)

julia> f(; d...)
22

Note the semicolon in the function call, which ensure that the elements in d are interpreted as keyword arguments instead of positional arguments which just happen to be Pairs.

Pass dictionaries in function as arguments

Change def merge(**dict): to def merge(*dict): and it is working. Avoid naming it dict since it is a keyword in python.

Passing a dictionary to as keyword parameters to a function

You are trying to pass additional argument which the function cannot accept.
One way to address this would be:

import numpy as np
import pandas as pd

sales_test = {'sale_1': 100,
'sale_2': 75,
'sale_3': 92,
'revenue_1' : 400,
'revenue_2' : 219,
'city' : 'London'
}

def get_sales(

with_fees: bool = True,**kwargs,
) -> float:
sale_1,sale_2,sale_3=kwargs['sale_1'],kwargs['sale_2'],kwargs['sale_3']
if with_fees is True:
return (sale_1 + sale_2 + sale_3) * 0.95
else:
return (sale_1 + sale_2 + sale_3)

def advanced_sales(
sales_test=None,
with_fees: bool = True,
) -> float:

sales = get_sales(**sales_test,with_fees=with_fees)
return sales

print(advanced_sales(sales_test))

keyword error generated when Passing a dictionary to a function with tuples as the keys

I performed a little example. It ist possible:

mydict = {('hostabc', 'pola'): 333444567, ('hostdef', 'polb'): 111222333, ('hostghi', 'polc'): 222999888}

def tupletest(kwargs):
for key in kwargs:
#print("key: %s , value: %s" % (key, kwargs[key]))
print(key[0])
print(key[1])

tupletest(mydict)

I hope this helps you. I also implemented a little example for entering the key of the dictionary.

Output

How to pass dictionary items as function arguments in python?

If you want to use them like that, define the function with the variable names as normal:

def my_function(school, standard, city, name):
schoolName = school
cityName = city
standardName = standard
studentName = name

Now you can use ** when you call the function:

data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}

my_function(**data)

and it will work as you want.

P.S. Don't use reserved words such as class.(e.g., use klass instead)

Is it possible to pass a dictionary as function parameters in R?

R doesn’t have a built-in dictionary data structure. The closest equivalent, depending on your use-case, is either a named vector, a named list, or an environment.

So, in your case, you’d define params as

params = list(param1 = 1, param2 = 'str', param3 = TRUE} 

… of course this doesn’t allow using variables for the names, but you can assign the names after the fact to fix that, or use setNames; e.g.:

params = setNames(list(1, 'str', TRUE), paste0('param', 1 : 3))

These work “well enough”, as long as your dictionary keys are strings. Otherwise, you’ll either need a data.frame with a lookup key column and a value column, or a proper data structure.

Correspondingly, there’s also no specific syntactic sugar for the creation of dictionaries. But R’s syntax is flexible, so we can have some fun.

R also doesn’t have a splat operator as in Python, but R has something much more powerful: thanks to metaprogramming, we can generate dynamic function call expressions on the fly. And since calling functions with a list of parameters is such a common operation, R provides a special wrapper for it: do.call.

For instance (using the code from the above link for the syntactic sugar to generate dictionaries):

params = dict('param1': 1, 'param2': 'str', 'param3': TRUE)

myfunc = function (param1, param2, param3) {
toString(as.list(environment()))
}

do.call('myfunc', params)
# [1] "1, str, TRUE"

Optionally passing an extra dictionary to a method / function

What is happening here is that you've defined a function that only has two positional arguments, and you're trying to give it 3, just as the error-message is telling you.

If we look at your code, then it doesn't look like you're trying to use keyword-arguments either so the **kwargs argument doesn't get used.

With just a minor change to your code we can get the result you want:

def create_objection(name, position, *args):
dicct = {'name': name,
'position': position}
if args:
dicct["extra_info"] = args
return dicct

x = create_objection('c1', {'t': 1})
z = create_objection('c1', {'t': 1}, {'whatever': [3453, 3453]}, {'whatever2': [34, 34]})

print(x)
print(z)

Output:

{'name': 'c1', 'position': {'t': 1}}
{'name': 'c1', 'position': {'t': 1}, 'extra_info': ({'whatever': [3453, 3453]}, {'whatever2': [34, 34]})}

If you also want to include other keyword-arguments, then you can just do another loop over that variable like so:

def create_objection(name, position, *args, **kwargs):
dicct = {'name': name,
'position': position}
if args:
dicct["extra_info"] = args
for key, value in kwargs.items():
dicct[key] = value
return dicct

y = create_objection('c1', {'t': 1}, {'whatever': [3453, 3453]}, thisisakeyword="totally a keyword!")
print(y)

Output:

{'name': 'c1', 'position': {'t': 1}, 'extra_info': ({'whatever': [3453, 3453]},), 'thisisakeyword': 'totally a keyword!'}


Related Topics



Leave a reply



Submit