python字典中的关键字循环值再循环_在字典中列出,在Python中循环

这段博客内容涉及一个Python代码示例,该代码旨在处理电子邮件头部签名的验证。原始代码在遍历嵌套字典中的列表时遇到了`TypeError`,即字符串索引必须为整数。博主提供了错误的代码片段,并详细解释了问题所在。解决方案是正确地遍历字典和其内部的签名列表。修复后的代码避免了变量名冲突,简化了结构,并可能提高了效率。
摘要由CSDN通过智能技术生成

I have the following code:

TYPES = {'hotmail':{'type':'hotmail', 'lookup':'mixed', 'dkim': 'no', 'signatures':['|S|Return-Path: postmaster@hotmail.com','|R|^Return-Path:\s*[^@]+@(?:hot|msn)','^Received: from .*hotmail.com$']},

'gmail':{'type':'gmail', 'lookup':'mixed', 'dkim': 'yes', 'signatures':['|S|Subject: unsubscribe','','','']}

}

for type_key, type in TYPES.iteritems():

for sub_type_key, sub_type in type.iteritems():

for sig in sub_type['signatures']:

if ("|S|" in sig):

#String based matching

clean_sig = sig[3:len(sig)]

if (clean_sig in file_contents):

sig_match += 1

elif ("|R|" in sig):

clean_sig = sig[3:len(sig)]

#REGMATCH later

if (sig_match == sig.count):

return sub_type['type']

return None

However, it generates the error:

for sig in sub_type['signatures']:

TypeError: string indices must be integers, not str

I assume that it would see the list being pulled from dictionary element, and allow me to loop over that?

Python newbie is a newbie :(

解决方案for type_key, type in TYPES.iteritems():

for sub_type_key, sub_type in type.iteritems():

for sig in sub_type['signatures']:

should be:

for type_key, type in TYPES.iteritems():

for sig in type['signatures']:

But 'type' is a poor name choice in this case... you don't want to shadow a builtin.

Essentially, 'type_key' has the name (either 'hotmail' or 'gmail'), and 'type' has the dictionary that is the value associated with that key. So type['signatures'] is what you're wanting.

Also, you may not need to have 'gmail' inside the nested dictionary; just return 'type_key' instead of type['type'].

Bringing it all together, maybe this will work better: (Warning: untested)

providers = {

'hotmail':{

'type':'hotmail',

'lookup':'mixed',

'dkim': 'no',

'signatures':[

'|S|Return-Path: postmaster@hotmail.com',

'|R|^Return-Path:\s*[^@]+@(?:hot|msn)',

'^Received: from .*hotmail.com$']

},

'gmail':{

'type':'gmail',

'lookup':'mixed',

'dkim': 'yes',

'signatures':['|S|Subject: unsubscribe','','','']

}

}

for provider, provider_info in providers.iteritems():

for sig in provicer_info['signatures']:

if ("|S|" in sig):

#String based matching

clean_sig = sig[3:len(sig)]

if (clean_sig in file_contents):

sig_match += 1

elif ("|R|" in sig):

clean_sig = sig[3:len(sig)]

#REGMATCH later

if (sig_match == sig.count):

return provider

return None

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值