在Python中动态创建嵌套字典 [英] Create nested dictionary on the fly in Python

查看:873
本文介绍了在Python中动态创建嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to understand how to create nested dictionaries on the fly. Ideally my dictionary would look something like:

mydict = { 'Message 114861156': { 'email': ['user1@domain.com', 'user2@domain.com'] }, { 'status': 'Queued mail for delivery' }} 

这是我到目前为止所拥有的:

Here's what i have so far:

sampledata = "Message 114861156 to user1@domain.com user2@domain.com  [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'

如何动态制作像这样的嵌套字典?

How do you make a nested dictionary like this on the fly?

推荐答案

dict.setdefault是一个很好的工具,collections.defaultdict

dict.setdefault is a good tool, so is collections.defaultdict

您现在的问题是newdict是一个空字典,因此newdict[msgid]引用了不存在的键.这在分配事物(newdict[msgid] = "foo")时有效,但是由于newdict[msgid]最初未设置为 的任何内容,因此当您尝试对其进行索引时,会得到一个KeyError.

Your problem right now is that newdict is an empty dictionary, so newdict[msgid] refers to a non-existent key. This works when assigning things (newdict[msgid] = "foo"), however since newdict[msgid] isn't set to anything originally, when you try to index it you get a KeyError.

dict.setdefault让您回避最初说如果newdict中存在msgid,请给我其值.如果不存在,请将其值设置为{}并给我.

dict.setdefault lets you sidestep that by initially saying "If msgid exists in newdict, give me its value. If not, set its value to {} and give me that instead.

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用要调用的函数初始化,该函数生成一个容器,该容器将任何不存在的键都分配为值,例如

Using collections.defaultdict saves you the step of calling dict.setdefault. A defaultdict is initialized with a function to call that produces a container that any non-existent key gets assigned as a value, e.g.

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,我希望它成为一本新的词典.

You can use this to say "Hey if I talk to you about a new msgid, I want it to be a new dictionary.

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'] = ...

这篇关于在Python中动态创建嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆