python嵌套字典的建立_在Python中动态创建嵌套字典

1586010002-jmsa.png

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)

has the following output:

Traceback (most recent call last):

File "wildfires.py", line 57, in

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 is a good tool, so is collections.defaultdict

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 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!

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值