1

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

4 Answers4

4

** 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)
mgilson
  • 300,191
  • 65
  • 633
  • 696
1

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')
phihag
  • 278,196
  • 72
  • 453
  • 469
1

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.

brandizzi
  • 26,083
  • 8
  • 103
  • 158
0

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.

phihag
  • 278,196
  • 72
  • 453
  • 469
pcalcao
  • 15,789
  • 1
  • 44
  • 64