# What does the Double Star operator mean in Python?

The double star/asterisk (*) operator has more than one meaning in Python. We can use it as a exponential operator, used as function *kwargs, unpacking the iterables, and used to Merge the Dictionaries.

## Exponential operator

For numeric data the double asterisk (**) is used as an exponential operator. Let's take an example and see how the double star operator works on numeric operands.

### Example

The following example uses double asterisks/star (**) to calculate “a to the power b” and it works equivalent to the pow() function.

a = 10
b = 2
result = a ** b
print("a**b = ", result)


### Output

a**b =  100


## Creating a function with **kwargs

At the time of defining a function the double asterisk(**) is used to create a Python function with an arbitrary number of keyword arguments. It is nothing but a function that can accept any number of key−word arguments.

### Example

The above example is defined to take any number of keyword arguments.

def fun(**kwargs):
for k, v in kwargs.items():
print('key = {}, value = {}'.format(k,v))

fun(a=10, b=2, c=9, d=3, e=6)


### Output

key = a, value = 10
key = b, value = 2
key = c, value = 9
key = d, value = 3
key = e, value = 6


## Unpacking the iterables

When calling a function, the double asterisk/star (**) operator can be used as a parameter to unpack the keyword arguments.

To unpack the key as well as the values together from a Python dictionary, we can use the double−asterisk operator.

### Example

Using double star (**) operator we have unpacked the dictionary and sent the key value pairs to a function which accepts arbitrary number of keyword arguments.

def foo(**kwargs):
for key, value in kwargs.items():
if value > 90:
print(str(key) + " " + str(value))

d =  {'a': 100, 'b': 20, 'c': 96, 'd':101}
foo(**d)


### Output

a 100
c 96
d 101


## Merging the Dictionaries

By using the double star/asterisk operator we can merge two dictionaries in Python.

### Syntax

New_dict = {**dict1, **dict2}


The above syntax can create a new dictionary by unpacking the key−value pairs of existing dictionaries. If any duplicate keys present those are automatically resolved by this method.

### Example

The following example demonstrates how to merge the dictionaries, and double asterisk before dictionary object **dict can be used to unpack the dictionary.

d1 = {'A': 10, 'B': 20}
d2 = {'C': 30, 'D': 40}
print('initial dictionaries d1 = {} and d2 = {}: '.format(d1,d2))

z = {**d1, **d2}
print("Merged dictionary: ", z)


### Output

initial dictionaries d1 = {'A': 10, 'B': 20} and d2 = {'C': 30, 'D': 40}
Merged dictionary:  {'A': 10, 'B': 20, 'C': 30, 'D': 40}


Updated on: 09-Sep-2023

5K+ Views