I want to build a query for sunburnt(solr interface) using class inheritance and therefore adding key - value pairs together. The sunburnt interface takes keyword arguments. How can I transform a dict ({'type':'Event'}) into keyword arguments (type='Event')?
Use the double-star (aka double-splat?) operator:
func(**{'type':'Event'})
is equivalent to
func(type='Event')
** operator would be helpful here.
** operator will unpack the dict elements and thus **{'type':'Event'} would be treated as type='Event'
func(**{'type':'Event'}) is same as func(type='Event') i.e the dict elements would be converted to the keyword arguments.
FYI
* will unpack the list elements and they would be treated as positional arguments.
func(*['one', 'two']) is same as func('one', 'two')
Here is a complete example showing how to use the ** operator to pass values from a dictionary as keyword arguments.
>>> def f(x=2):
... print(x)
...
>>> new_x = {'x': 4}
>>> f() # default value x=2
2
>>> f(x=3) # explicit value x=3
3
>>> f(**new_x) # dictionary value x=4
4
Related
Example:
def somerando(a,b,c,d):
if not a+b+c+d == 9000:
return (a+b+c+d)
somerando(1,2,3,4)
Returns: 10
but
randonumbs = [1,2,3,4]
somerando(randonumbs)
Gives the following error:
TypeError Traceback (most recent call
last) in
----> 1 somerando(randonumbs)
TypeError: somerando() missing 3 required positional arguments: 'b',
'c', and 'd'
your function expects 4 arguments. randonumbs = [1,2,3,4] is a list (of four items); that is one argument for your function.
you could do this:
randonumbs = [1,2,3,4]
somerando(*randonumbs)
this usage of the asterisk (*) is discussed in this question or in PEP 3132.
You passed randonumbs as list, means this whole list is considered as first argument to the function somerando
You can use somerando(*randonumbs) .
Here, * means pass as tuple & ** means pass as dictionary (key, value pair) if you use ** in function parameters/ arguments.
Thank you.
The single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions, like below
randonumbs = [1,2,3,4]
somerando(*randonumbs)
The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function.
randonumbs = {'a':1, 'b':2, 'c': 3, 'd': 4}
somerando(**randonumbs)
Can anyone explain the difference when unpacking the dictionary using single or double asterisk? You can mention their difference when used in function parameters, only if it is relevant here, which I don't think so.
However, there may be some relevance, because they share the same asterisk syntax.
def foo(a,b)
return a+b
tmp = {1:2,3:4}
foo(*tmp) #you get 4
foo(**tmp) #typeError: keyword should be string. Why it bothers to check the type of keyword?
Besides, why the key of dictionary is not allowed to be non-string when passed as function arguments in THIS situation? Are there any exceptions? Why they design Python in this way, is it because the compiler can't deduce the types in here or something?
When dictionaries are iterated as lists the iteration takes the keys of it, for example
for key in tmp:
print(key)
is the same as
for key in tmp.keys():
print(key)
in this case, unpacking as *tmp is equivalent to *tmp.keys(), ignoring the values. If you want to use the values you can use *tmp.values().
Double asterisk is used for when you define a function with keyword parameters such as
def foo(a, b):
or
def foo(**kwargs):
here you can store the parameters in a dictionary and pass it as **tmp. In the first case keys must be strings with the names of the parameter defined in the function firm. And in the second case you can work with kwargs as a dictionary inside the function.
def foo(a,b)
return a+b
tmp = {1:2,3:4}
foo(*tmp) #you get 4
foo(**tmp)
In this case:
foo(*tmp) mean foo(1, 3)
foo(**tmp) mean foo(1=2, 3=4), which will raise an error since 1 can't be an argument. Arg must be strings and (thanks # Alexander Reynolds for pointing this out) must start with underscore or alphabetical character. An argument must be a valid Python identifier. This mean you can't even do something like this:
def foo(1=2, 3=4):
<your code>
or
def foo('1'=2, '3'=4):
<your code>
See python_basic_syntax for more details.
It is a Extended Iterable Unpacking.
>>> def add(a=0, b=0):
... return a + b
...
>>> d = {'a': 2, 'b': 3}
>>> add(**d)#corresponding to add(a=2,b=3)
5
For single *,
def add(a=0, b=0):
... return a + b
...
>>> d = {'a': 2, 'b': 3}
>>> add(*d)#corresponding to add(a='a',b='b')
ab
Learn more here.
I think the ** double asterisk in function parameter and unpacking dictionary means intuitively in this way:
#suppose you have this function
def foo(a,**b):
print(a)
for x in b:
print(x,"...",b[x])
#suppose you call this function in the following form
foo(whatever,m=1,n=2)
#the m=1 syntax actually means assign parameter by name, like foo(a = whatever, m = 1, n = 2)
#so you can also do foo(whatever,**{"m":1,"n":2})
#the reason for this syntax is you actually do
**b is m=1,n=2 #something like pattern matching mechanism
so b is {"m":1,"n":2}, note "m" and "n" are now in string form
#the function is actually this:
def foo(a,**b): # b = {"m":1,"n":2}
print(a)
for x in b: #for x in b.keys(), thanks to #vlizana answer
print(x,"...",b[x])
All the syntax make sense now. And it is the same for single asterisk. It is only worth noting that if you use single asterisk to unpack dictionary, you are actually trying to unpack it in a list way, and only key of dictionary are unpacked.
[https://docs.python.org/3/reference/expressions.html#calls]
A consequence of this is that although the *expression syntax may appear after explicit keyword arguments, it is processed before the keyword arguments (and any **expression arguments – see below). So:
def f(a, b):
print(a, b)
f(b=1, *(2,))
f(a=1, *(2,))
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#TypeError: f() got multiple values for keyword argument 'a'
f(1, *(2,))
>>> class Test(object):
>>> def test(self,*arg):
>>> print(arg[0],arg[1])
>>> p = Test()
>>> t = 2,3
>>> p.test(t)
gives me IndexError: tuple index out of range
why is that? and how do i get the value for that tuple?
You passed in just one argument (the whole tuple (2, 3)), so only arg[0] exists; if you meant the tuple values to be separate arguments, apply them with the *args call syntax:
p.test(*t)
The alternative is to not use the *arg catchall argument in your function definition:
def test(self, arg):
Now your function has two normal positional arguments, self and arg. You can only pass in one argument, and if that is your tuple, arg[0] and arg[1] will work as expected.
Using your demo class:
>>> class Test(object):
>>> def test(self,*arg):
>>> print(arg[0],arg[1])
When doing this:
>>> p = Test()
>>> t = 2,3
>>> p.test(t)
arg will have a value of [(1,2),]
When doing this:
>>> p = Test()
>>> t = 2,3
>>> p.test(*t)
arg will have a value of [1,2]
The * in the function means that all remaining arguments (non-keyword) are put into a list for you.
In the first case you send (1,2) has a single argument. In the second case the tuple is made into individual arguments using the * thus you send in 1 and 2.
For complete documentation on this refer to this Python article:
http://docs.python.org/2/reference/expressions.html#calls
This question already has answers here:
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
(25 answers)
Closed 9 years ago.
here is a small portion of code
import networkx as nx
G=nx.MultiDiGraph()
...
G.add_edge(white, black, **game)
(game is a dictionnary)
what is the role of ** in the last line
** is the operator which unpacks mapping types (e.g. a dict) into keyword arguments.
Consider:
def foo(bar=1):
print bar
d = {'bar':2}
foo(**d)
In this example, 2 will be printed. On the other side, you can also absorb all unknown keyword arguments in a **kwargs type variable:
def foo(a=1,b=2,**kwargs):
print kwargs
foo(a=1,b=2,c=3)
Of course, you can combine these forms as well:
def foo(a=1,b=2,**kwargs):
print b
print kwargs
d = {'b':3, 'c':4}
foo(**d)
The function add_edge gets passed in the dictionary game as keyword arguments. For example, the following two are equivalent:
game = {'weight': 5, 'color': 'blue'}
G.add_edge(white, black, **game)
G.add_edge(white, black, weight=5, color='blue')
It expands a dictionary so its key-pair values are used as named parameters. Consider, for example, this function:
>>> def f(a, b, c):
... return a+b-c
...
I can call it passing its arguments in the original order:
>>> f(1,2,3)
0
But I can also switch them if I attribute values to the argument names:
>>> f(1,c=3,b=2)
0
When one calls a function passing a dictionary preceded by **, the pairs of this dictionary will be used as parameters. So, I could create the dictionary below
>>> params = {'c':3, 'b':2}
...and pass it to my function...
>>> f(1,**params)
0
...and will get the same result.
It means that the argument is a dictionary, basically.
It's usually used as **kwargs, meaning, keyword arguments.
For instance, when you define a method like:
def myMethod(first, *args, **kwargs):
....
It means that the second argument is expected to be a collection (a "list" of arguments), and kwargs is meant to be a dict.
So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.
a = [[1,2],[3,4]]
def cord():
return 1, 1
def printa(y,x):
print a[y][x]
printa(cord())
...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice.
Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this?
printa(*cord())
The * here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.
It's basically the reverse of the * you might use to capture all non-keyword arguments in a function definition:
def fn(*args):
# args is now a tuple of the non-keyworded arguments
print args
fn(1, 2, 3, 4, 5)
prints (1, 2, 3, 4, 5)
fn(*[1, 2, 3, 4, 5])
does the same.
Try this:
>>> def cord():
... return (1, 1)
...
>>> def printa(y, x):
... print a[y][x]
...
>>> a=[[1,2],[3,4]]
>>> printa(*cord())
4
The star basically says "use the elements of this collection as positional arguments." You can do the same with a dict for keyword arguments using two stars:
>>> a = {'a' : 2, 'b' : 3}
>>> def foo(a, b):
... print a, b
...
>>> foo(**a)
2 3
Actually, Python doesn't really return multiple values, it returns one value which can be multiple values packed into a tuple. Which means that you need to "unpack" the returned value in order to have multiples.
A statement like
x,y = cord()
does that, but directly using the return value as you did in
printa(cord())
doesn't, that's why you need to use the asterisk. Perhaps a nice term for it might be "implicit tuple unpacking" or "tuple unpacking without assignment".