如何根据匹配的顶级键将元素从一个字典插入另一个字典

时间:2019-01-10 18:01:49

标签: python python-3.x

我有一个需要填写的字典清单。它具有客户服务案例编号的顶级标识符。我还有另一本词典,其中列出了与案例有关的所有电子邮件信息-这些词典中也有与电子邮件相关的案例号。

我正在尝试分解电子邮件列表,并将它们与第一个案件列表关联起来。

我正在使用简单Salesforce软件包提取信息。

#First dictionary:

Cases =
    [{CaseNumber : "1",
     Date: "value",
     Reason: "value",
     Emails: NONE (need to add here)},
     {CaseNumber : "2",
     Date: "value",
     Reason: "value",
     Emails: NONE (need to add here)}]

#etc.  this list is a set of dictionaries of all the cases related to an order #number that is passed in previously.

#The second list of is a list of all of the emails related to the above cases -

Emails =
    [{CaseNumber : "1",
     Date: "value",
     EmailBody: "value",},
     {CaseNumber : "1",
     Date: "value",
     EmailBody: "value",},
     {CaseNumber : "2",
     Date: "value",
     EmailBody: "value",}]

#So this list needs to get nested accordingly to the Emails key by matching on case number

Cases =
    [{CaseNumber : "1",
     Date: "value",
     Reason: "value",
     Emails: emails[1,2,etc]},
     {CaseNumber : "2",
     Date: "value",
     Reason: "value",
     Emails: emails[3,4,etc]}]

应创建与顶级案例ID相关的嵌套字典的列表。

1 个答案:

答案 0 :(得分:0)

可能不是最快的解决方案,但是我会浏览电子邮件并根据CaseNumber将其分组。这将是基于该值的电子邮件列表。由此,您可以遍历每种情况,抓住CaseNumber,然后将列表插入字典的Emails部分

from collections import defaultdict

e = defaultdict(list)

for email in Emails:
    case = email.get('CaseNumber')
    e[case].append(email)

for case in Cases:
     casenumber = case.get('CaseNumber')
     case['Emails'] = e[casenumber]

# Cases now looks like [{'CaseNumber': '0', 'Emails': [{'EmailBody': 'value'},...], {'CaseNumber': '1', 'Emails': [{'EmailBody': 'value',...}]}]

defaultdict是一个字典,如果不存在键,它将插入一个列表,从而允许e[key].append()调用而无需检查键是否在字典中。文档是here

编辑:

出于完整性考虑,在没有 defaultdict的情况下执行此操作的方式如下:

e = {}
for email in Emails:
    case = email.get('CaseNumber')
    if not case in e:
        # create single element list if key not in dictionary
        e[case] = [email]
    else:
        e[case].append(email)

简而言之,您可以使用get来完全避免使用KeyErrors

for email in Emails:
    case = email.get('CaseNumber')
    e[case] = e.get(case, []).append(email)

get处将返回与case关联的值或指定为第二个参数的默认值(此处为list