Is there any way to print **kwargs in Python

Question:

I am just curious about **kwargs. I am just started learning it, So while going through all the question on stackoverflow and video tutorials I notice we can do like this

def print_dict(**kwargs):
    print(kwargs)
print_dict(x=1,y=2,z=3)  

Which gives output as :{'y': 2, 'x': 1, 'z': 3}
So I figures why not do the reverse and print the like x=1,y=2,z=3

So I tried this:

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

But I got an error like : TypeError: 'z' is an invalid keyword argument for this function(sometimes it shows ‘y’ is an invalid keyword).

I also tried like assign it to the variable and then print it but again i got an error (SyntaxError: invalid syntax):

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

See this is working:

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

But instead of print(this) if i do print(**this) it gives the error.

As we can print *arg as I try this code:

def num(*tuple_num):
    print(tuple_num)
    print(*tuple_num)
num(1,2,3,4)

It run perfectly and gives output as:

(1, 2, 3, 4)
1 2 3 4

So I want to know is there any possible solution/way to print **kwargs ?

Asked By: Kalpesh Dusane

||

Answers:

You have to build your own formatting for dictionaries (nothing else are **kwargs):

print(','.join('{0}={1!r}'.format(k,v) for k,v in this.items()))
Answered By: Daniel

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()]))
Answered By: Martijn Pieters

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'}
Answered By: Keno

Pretty printing kwargs is easy with the pprint package:

from pprint import pprint
pprint(kwargs)

Example output from a call to requests.get:

{'allow_redirects': True, 'verify': False}
Answered By: Andy Brown

A simplification of the answer from @keno:

Use f-string :

print(f"{kwargs}")
Answered By: WestCoastProjects
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.