How do I loop through **kwargs in Python?

不问归期 提交于 2019-12-03 09:36:01
jterrace

For Python 3 users:

You can iterate through kwargs with .items()

subject = obj.subject
body = obj.body
for 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.subject
body = obj.body
for 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.subject
body = obj.body
for 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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!