试图了解如何动态创建嵌套字典。理想情况下,我的字典应类似于:
mydict = { 'Message 114861156': { 'email': ['[email protected]', '[email protected]'] }, { 'status': 'Queued mail for delivery' }}
这是我到目前为止的内容:
sampledata = "Message 114861156 to [email protected] [email protected] [InternalId=260927844] Queued mail for delivery'."
makedict(sampledata)
def makedict(results):
newdict = {}
for item in results:
msgid = re.search(r'Message \d+', item)
msgid = msgid.group()
newdict[msgid]['emails'] = re.findall(r'\w+@\w+\.\w+', item)
newdict[msgid]['status'] = re.findall(r'Queued mail for delivery', item)
具有以下输出:
Traceback (most recent call last):
File "wildfires.py", line 57, in <module>
striptheshit(q_result)
File "wildfires.py", line 47, in striptheshit
newdict[msgid]['emails'] = re.findall(r'\w+@\w+\.\w+', item)
KeyError: 'Message 114861156'
您如何动态制作这样的嵌套字典?
dict.setdefault
是一个很好的工具,所以也是 collections.defaultdict
您现在的问题是这newdict
是一个空字典,因此newdict[msgid]
是指不存在的键。这在分配事物(newdict[msgid] = "foo"
)时起作用,但是由于本来newdict[msgid]
没有设置任何东西,因此当您尝试对其进行索引时,会得到一个。KeyError
dict.setdefault
通过最初说“如果msgid
存在于中newdict
,请给我它的值。如果不存在,请将其值设置为,{}
然后给我,让您回避。
def makedict(results):
newdict = {}
for item in results:
msgid = re.search(r'Message \d+', item).group()
newdict.setdefault(msgid, {})['emails'] = ...
newdict[msgid]['status'] = ...
# Now you KNOW that newdict[msgid] is there, 'cuz you just created it if not!
使用collections.defaultdict
可以节省呼叫的步骤dict.setdefault
。使用defaultdict
要调用的函数初始化A ,该函数产生一个容器,该容器将不存在的任何键都分配为值,例如
from collections import defaultdict
foo = defaultdict(list)
# foo is now a dictionary object whose every new key is `list()`
foo["bar"].append(1) # foo["bar"] becomes a list when it's called, so we can append immediately
您可以这样说:“嘿,如果我与您讨论新的msgid,我希望它是一本新的词典。
from collections import defaultdict
def makedict(results):
newdict = defaultdict(dict)
for item in results:
msgid = re.search(r'Message \d+', item).group()
newdict[msgid]['emails'] = ...
newdict[msgid]['status'] = ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句