在Python中动态创建嵌套字典

多布斯

试图了解如何动态创建嵌套字典。理想情况下,我的字典应类似于:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章