如何简化这些字典理解?

问题描述 投票:1回答:2

下面的代码正在工作,并带来了我想要的结果。但是,我无法将两组包含两个字典的理解转换为两个字典。有可能吗?

dicTfAll={1:{'c1': ['aa','bb','cc']},
         2:{'c1': ['dd','ee','ff']}}


dicTf={1:{'c2': ['aax','bbx','cc']},
         2:{'c2': ['ddy','eey','ff']},
         3: {'c2': ['xx', '11']}}

allKeys=list(dicTfAll.keys())
dicTfAllP1={item[0]:item[1]  for item in dicTf.items() if item[0] not in allKeys}
dicTfAllP2={item[0]:dict(dicTfAll[item[0]],**item[1])  for item in dicTf.items() if item[0] in allKeys}
dicTfAllP=dicTfAllP1
dicTfAllP.update(dicTfAllP2)
# I use at this point dicTfAllP to do a lot of calculations. 
# dicTfAllP has the same form but very different values. 
allKeys=list(dicTfAllP.keys())
listOfCompanies=['c1','c2']
outputCompanies={}
for company in listOfCompanies:
    theKeys=[key for key in allKeys if company in dicTfAllP[key]]
    outputCompanies[company]={token:key  for key in theKeys for token in dicTfAllP[key][company]}

确切地说,我想以一种字典理解的方式在下面转换这些行[它生成嵌套的字典,它是上述字典的合并]:

allKeys=list(dicTfAll.keys())
dicTfAllP1={item[0]:item[1]  for item in dicTf.items() if item[0] not in allKeys}
dicTfAllP2={item[0]:dict(dicTfAll[item[0]],**item[1])  for item in dicTf.items() if item[0] in allKeys}

此外,我也想以一种字典理解的方式在下面转换这些行[它构建了一个嵌套的字典,用于恢复原始字典(在合并之前):]]

outputCompanies={}
for company in listOfCompanies:
    theKeys=[key for key in allKeys if company in dicTfAllP[key]]
    outputCompanies[company]={token:key  for key in theKeys for token in dicTfAllP[key][company]}

我特别担心实施效率。如果我需要保持这种结构怎么办?我必须保持这种结构,因为我必须在两组dict理解之间进行大量计算。

下面的代码正在工作,并带来了我想要的结果。但是,我无法将两组包含两个字典的理解转换为两个字典。那可能吗? ...

python python-3.x dictionary list-comprehension dictionary-comprehension
2个回答
2
投票

理解是python的一个惊人功能,但它们并不总是最好的情况。与其创建大量变量并将它们混在一起,不如一次处理一个变量。我敢肯定有可能从这段代码中榨取更多的汁,但是这应该在可读性和处理能力之间取得很好的平衡。我检查了输出以确保它与您的代码的输出匹配。


0
投票

您可以使用此理解来构建dicTfAllP:

© www.soinside.com 2019 - 2024. All rights reserved.