问题
In the code below, I want to read obj.subject and place it into var subject, also read obj.body and place it into body. First I want to read the kwargs variables and search for keywords within the string to replace, if none exists then move on.
How can I iterate through kwargs in Python?
for key in kwargs:
subject = str(obj.subject).replace('[%s]' % upper(key), kwargs[key])
for key in kwargs:
body = str(obj.body).replace('[%s]' % upper(key), kwargs[key])
return (subject, body, obj.is_html)
回答1:
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)
回答2:
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.
来源:https://stackoverflow.com/questions/8899129/how-do-i-loop-through-kwargs-in-python