在字典中列出,在Python中循环 [英] List in a dictionary, looping in Python
问题描述
我有以下代码:
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
但是,它会产生错误:
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新手是新手:(
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']:
应为:
for type_key, type in TYPES.iteritems():
for sig in type['signatures']:
但是在这种情况下,'type'是一个糟糕的名字选择……您不想隐藏内置函数.
But 'type' is a poor name choice in this case... you don't want to shadow a builtin.
本质上,"type_key"具有名称("hotmail"或"gmail"),而"type"具有字典,即与该键关联的值.因此,您需要的是type ['signatures'].
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.
此外,您可能不需要在嵌套字典中添加"gmail";只需返回'type_key'而不是type['type']
.
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
这篇关于在字典中列出,在Python中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!