簡體   English   中英

Python - 從具有重復元素的兩個列表創建字典

[英]Python - create dictionary from two lists with repeated elements

嘗試使用 zip() 從兩個列表(鍵和值)創建一個字典,其中有一個重復的鍵元素。 我想要的是字典有一個重復元素的鍵,並且對應的值是重復值的總和。

lst1 = ['a', 'b', 'c', 'd', 'b']
lst2 = [2, 3, 4, 5, 6]
new_dictionary = dict(zip(lst1,lst2))
print(new_dictionary)

實際 output: {'a': 2, 'b': 6, 'c': 4, 'd': 5}

所需的 output: {'a': 2, 'b': 9, 'c': 4, 'd': 5}

如果您使用defaultdict ,則可以將類型設置為int 這將讓您簡單地添加它:

from collections import defaultdict

new_dictionary = defaultdict(int)

lst1 = ['a', 'b', 'c', 'd', 'b']
lst2 = [2, 3, 4, 5, 6]

for k, n in zip(lst1,lst2):
    new_dictionary[k] += n
    
print(new_dictionary)
# defaultdict(<class 'int'>, {'a': 2, 'b': 9, 'c': 4, 'd': 5})

您也可以通過簡單地使用new_dictionary = Counter() collections.Counter()以相同的方式使用 collections.Counter() 。

這里有一個方法:

lst1 = ['a', 'b', 'c', 'd', 'b']
lst2 = [2, 3, 4, 5, 6]
new_dictionary = {}

for key, value in zip(lst1, lst2):
    if key in new_dictionary:
        new_dictionary[key] += value
    else:
        new_dictionary[key] = value

print(new_dictionary)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM