Is there any way to print **kwargs in Python

The syntax callable(**dictionary) applies the dictionary as if you used separate keyword arguments.

So your example:

mydict = {'x':1,'y':2,'z':3}
print(**mydict)

Is internally translated to:

print(x=1, y=2, z=3)

where the exact ordering depends on the current random hash seed. Since print() doesn't support those keyword arguments the call fails.

The other print() call succeeds, because you passed in the values as separate positional arguments:

tuple_num = (1, 2, 3, 4)
print(*tuple_num)

is effectively the same as:

print(1, 2, 3, 4)

and the print() function supports separate arguments by writing them out one by one with the sep value in between (which is a space by default).

The **dictionary is not valid syntax outside of a call. Since callable(**dictionary) is part of the call syntax, and not an object, there is nothing to print.

At most, you can format the dictionary to look like the call:

print(', '.join(['{}={!r}'.format(k, v) for k, v in mydict.items()]))

Using f-strings in python 3 works for me:

def mixAndMatch(*args, **kwargs):
    print(f' Args: {args}' )
    print(f' Kwargs: {kwargs}' )

mixAndMatch('one', 'two', arg3 = 'three', arg4 = 'four’)


>>>
Args: ('one', 'two')
Kwargs: {'arg3': 'three', 'arg4': 'four'}

Tags:

Python