[英]Creating a dictionary with multiple values per key from a list of dictionaries
我有以下词典列表:
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
值,而不是将它们添加到列表的末尾。
我怎样才能解决这个问题?...
目前尚不清楚为什么需要这样的输出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]}
通过该命令获得所需的输出要容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.