获取嵌套字典中重复键的总数

时间:2018-08-02 11:10:25

标签: python dictionary data-science

基本上我有这样的数据框

localStorage

我将其转换成这样的字典

   col1           col2         col3    col4
1. 554862122    55110385224      PR    26                                    
2. 5242700637   55110385236      CO    246
3. 560297164    55110385250      CO    109
4. 5651138615   55110385266      PR    26
5. 5242699687   55110385289      CO    109

但是现在我想要这个但没有循环

{554862122: {55110385224:  {'PR 26': 2})},
5242699687: {55110385289:  {'CO 109': 6}),
554862121: {55110385224:  {'PR 26': 3})}" 

1 个答案:

答案 0 :(得分:0)

您可以使用嵌套循环遍历子字典,并使用dict.setdefault来初始化输出字典中的子列表:

d = {
    554862122: {55110385224:  {'PR 26': 2}},
    5242699687: {55110385289:  {'CO 109': 6}},
    554862121: {55110385224:  {'PR 26': 3}}
}
o = {}
for k, v in d.items():
    for l, w in v.items():
        for m, x in w.items():
            o[m][0] = o.setdefault(m, [0])[0] + x
            o[m].append([k, l])
print(o)

这将输出:

{'PR 26': [5, [554862122, 55110385224], [554862121, 55110385224]], 'CO 109': [6, [5242699687, 55110385289]]}