[英]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.