从字典列表中创建每个键有多个值的字典

2024-06-07 09:53:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字典清单:

listofdics = [{'StrId': 11, 'ProjId': 1},{'StrId': 11,'ProjId': 2},
              {'StrId': 22, 'ProjId': 3},{'StrId': 22, 'ProjId': 4},
              {'StrId': 33, 'ProjId': 5},{'StrId': 33, 'ProjId': 6},
              {'StrId': 34, 'ProjId': 7}]

我需要为StrId获取所有重复的ProjId值。这就是我要找的输出:

^{pr2}$

我编写了一个函数来创建一个字典列表,其中StrId值作为键,以及一个列表,其中包含与值共享相同键的所有ProjId。这里是:

def compare_projids(listofdics):
    proj_ids_dups = {} 

    for row in listofdics:       
        id_value = row['StrId']
        proj_id_value = row['ProjId']
        proj_ids_dups[id_value]=proj_id_value

        if row['StrId'] == id_value:
            sum_ids = []
            sum_ids.append(proj_id_value)  
        proj_ids_dups[id_value]=sum_ids
     return proj_ids_dups

这是我现在得到的输出:

new_listofdics=  {33: [6], 34: [7], 11: [2], 22: [4]}

我看到的是append用最后一个迭代的值替换每个ProjId值,而不是将它们添加到列表的末尾。在

我该怎么解决这个问题呢?。。。在


Tags: 函数idids列表字典valuerowproj
1条回答
网友
1楼 · 发布于 2024-06-07 09:53:08

不清楚为什么需要这样的输出new_listofdics = [{11:[1,2]}, {22:[3,4]}, {33:[5,6]], {34:[7]}],因为最好只使用dict对象。在

所以程序应该是这样的

>>> from collections import defaultdict
>>> listofdics = [{'StrId': 11, 'ProjId': 1},{'StrId': 11,'ProjId': 2},
              {'StrId': 22, 'ProjId': 3},{'StrId': 22, 'ProjId': 4},
              {'StrId': 33, 'ProjId': 5},{'StrId': 33, 'ProjId': 6},
              {'StrId': 34, 'ProjId': 7}]
>>> output = defaultdict(list)
>>> for item in listofdics:
...     output[item.get('StrId')].append(item.get('ProjId'))
>>> dict(output)
{11: [1, 2], 22: [3, 4], 33: [5, 6], 34: [7]}

更容易理解你想要的输出。在

相关问题 更多 >

    热门问题