Python3:将两组字典添加到新格式中

时间:2014-10-16 01:23:43

标签: python-3.x dictionary list-comprehension

我有两本词典,

MaleDict = {'Jason':[(2014, 394),(2013, 350)...], 
            'Stephanie':[(2014, 3), (2013, 21),..]....}
FemaleDict = {'Jason':[(2014, 56),(2013, 23)...], 
              'Stephanie':[(2014, 335), (2013, 217),..]....}

我正在尝试添加它们以便

CompleteDict = {'Jason':[(2014, 394, 56),(2013, 350, 23)...], 
                'Stephanie':[(2014, 3, 335), (2013, 21, 217),..]....}

我创建了一个列表推导,当每个词典都存在那一年时,它完成了任务。但是,即使年份不存在于MaleDict或FemaleDict中,我也需要输出。例如,如果一年不在MaleDict中,那么代码就会读到......'Stephanie':[.....,(1999,0,389),....] ......

我的列表理解是

for name_key in name_keys:
    for year_key in year_keys:
        [BaseDict[name_key].append((year_key, a[1], b[1])) for a in MaleDict[name_key] for b in FemaleDict[name_key] if (year_key == a[0] == b[0])]

    #This is where I am stuck. My list comprehensions dont work when there is no value for a specific year
        [BaseDict[name_key].append((year_key, a[1], 0)) for a in MaleDict[name_key] for b in FemaleDict[name_key] if (year_key == a[0] != b[0])]
        [BaseDict[name_key].append((year_key, 0, b[1])) for a in MaleDict[name_key] for b in FemaleDict[name_key] if (year_key != a[0] == b[0])]
print(BaseDict)

1 个答案:

答案 0 :(得分:0)

如果您的数据格式不合理,我会考虑使用defaultdict中的collections
而不是[(2014, 394),(2013, 350)...] 使用collections.defaultdict(int, {2014: 394, 2013: 350})等 然后你可以使用

for name_key in name_keys:
    for year_key in year_keys:
        CompleteDict[name_key].update([FemaleDict[year_key], MaleDict[year_key]])

CompleteDict['Stephanie'][1999]将成为[0, 389]