【问题标题】:Creating a dictionary with multiple values per key from a list of dictionaries从字典列表中创建每个键具有多个值的字典
【发布时间】:2016-10-02 16:01:12
【问题描述】:

我有以下字典列表:

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 值。所以这是我正在寻找的输出:

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 值替换为最后一个迭代的值,而不是将它们添加到列表的末尾。

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

【问题讨论】:

  • 不是append。您每次都使用sum_ids = [] 创建一个新的列表对象

标签: python dictionary


【解决方案1】:

不清楚为什么你需要有这样的输出 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]}

通过您想要的输出的字典要容易得多。

【讨论】:

  • 而且您总是可以通过这种方式获得所需的输出:[{k: v} for k, v in output.items()]
猜你喜欢
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多