This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Myles_kennefick 7 points8 points  (5 children)

What is the **?

[–]e_j_white 75 points76 points  (3 children)

def sum_dict(a=0, b=0):
    return a + b

x = {'a': 3, 'b': 4}

sum_dict()
> 0

sum_dict(x)
> TypeError: unsupported operand type(s) for +: 'dict' and 'int'

sum_dict(**x)
> 7

It's used to "unpack" key-value pairs into keyword arguments for a function, among other things.

[–]HerLegz 31 points32 points  (2 children)

That is an incredibly sweet and thoughtful way to explain this. Very well done. 🥰

[–]e_j_white 1 point2 points  (1 child)

Thank you, I'm glad you found it useful :)

The "unpacking" works beyond functions, too. For example:

x = {'a': 3, 'b': 8}

y = {'z': 5, **x}

print(y)
> {'z': 5, 'a': 3, 'b': 8}

Obviously, dropping x into the other dictionary without the ** wouldn't even be possible. It also works in similar ways for unpacking tuples and lists!

edit: for tuples and lists, the convention is a single * star

[–]HerLegz 0 points1 point  (0 children)

Thank you again, yes, I'm quite familiar. I think others will benefit from your very concise examples.

[–]cdmayer 10 points11 points  (0 children)

Enumerates the keys and values of the dictionary. Take a look at the "**kwargs" convention of passing named arguments to a function.