简体   繁体   English

如何在 Python 中循环遍历 **kwargs?

[英]How do I loop through **kwargs in Python?

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 .在下面的代码中,我想读取obj.subject并将其放入 var subject,同时读取obj.body并将其放入body First I want to read the kwargs variables and search for keywords within the string to replace, if none exists then move on.首先,我想读取kwargs变量并在字符串中搜索要替换的关键字,如果不存在则继续。

How can I iterate through kwargs in Python?如何在 Python 中遍历kwargs

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)

For Python 3 users:对于 Python 3 用户:

You can iterate through kwargs with .items()您可以使用.items()遍历kwargs

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:对于 Python 2 用户:

You can iterate through kwargs with .iteritems() :您可以使用.iteritems()遍历kwargs

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.对于那些升级到 Python 3 的人来说,这是一个简短的说明。

In Python 3 it's almost the same:在 Python 3 中,它几乎是一样的:

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 .请注意, iteritems()变为items()因为dict不再具有iteritems方法。

you can iter on the dictionary as it provides by default iteration on its key.您可以对字典进行迭代,因为它默认提供对其键的迭代

subject = obj.subject
body = 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.我在Python 3Python 2解释器上测试了它,它对我来说完全正常,所以它也适合你。 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.所有结构都有一个默认值,无论是列表、字典还是元组,您都可以在 python 语言中轻松对其进行迭代。

Attaching a photo depicting that we can do that so easily .附上一张照片,说明我们可以如此轻松地做到这一点 照片证明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM