How do I loop through **kwargs in Python? How do I loop through **kwargs in Python? python python

How do I loop through **kwargs in Python?


For Python 3 users:

You can iterate through kwargs with .items()

subject = obj.subjectbody = obj.bodyfor key, value in kwargs.items():    subject = subject.replace('[%s]' % key.toupper(), value)    body = body.replace('[%s]' % key.toupper(), value)return (subject, body, obj.is_html)

For Python 2 users:

You can iterate through kwargs with .iteritems():

subject = obj.subjectbody = obj.bodyfor key, value in kwargs.iteritems():    subject = subject.replace('[%s]' % key.toupper(), value)    body = body.replace('[%s]' % key.toupper(), value)return (subject, body, obj.is_html)


Just a quick note for those upgrading to Python 3.

In Python 3 it's almost the same:

subject = obj.subjectbody = obj.bodyfor key, value in kwargs.items():    subject = subject.replace('[{0}]'.format(key.toupper()), value)    body = body.replace('[{0}]'.format(key.toupper()), value)return (subject, body, obj.is_html)

Notice that iteritems() becomes items() as dict no longer has the method iteritems.


you can iter on the dictionary as it provides by default iteration on its key.

subject = obj.subjectbody = obj.body    for key in kwargs:    subject = str(subject).replace([%s] % upper(key), kwargs[key])    body = str(body).replace([%s] % upper(key), kwargs[key])print(subject, body)

I tested it on Python 3 and Python 2 Interpreters and it is working totally fine for me so it will also work fine for you. There is a default for all the structures whether its List or Dictionary or tuple you can Iter on it easily in the python language.

Attaching a photo depicting that we can do that so easily.Photo For Proof