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

时间:2016-10-02 16:01:13

标签: python dictionary

我有以下词典列表:

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}]

我需要获得重复的ProjId的所有StrId值。所以这是我正在寻找的输出:

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

我编写了一个函数,用于创建一个以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值替换为最后一个迭代值,而不是在列表末尾添加它们。

我该如何解决这个问题?...

1 个答案:

答案 0 :(得分:2)

目前还不清楚为什么你需要输出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]}

通过那个你想要的输出的字典会更容易。

相关问题