[英]Adding Items in a List to a Dictionary - Python
我正在嘗試將項目添加到詞典的列表中。 我有兩個列表:x_list和y_list。 我試圖使x_list鍵和y_list值。 我已經嘗試過使用zip方法,但是我確實需要一個一個地添加它們。 現在我有:
dictionary = dict((x,0) for x in x_list)
但我想要這樣的東西:
dictionary = dict((x,y) for x in x_list, for y in y_list)
但這顯然會造成語法錯誤。 有什么辦法嗎? 謝謝!
編輯:
我已經嘗試過壓縮並且可以正常工作,謝謝,但是我需要將這些項目一個接一個地添加到字典中(我試圖讓具有相同鍵的條目將值加在一起,例如apple:10和apple:5成為蘋果:15)
例如:
x_list = (blue, orange, purple, green, yellow, green, blue)
y_list = (1, 2, 5, 2, 4, 3, 8)
我希望輸出是
dictionary = {blue:9, orange:2, purple:5, green:5, yellow:4}
並且列表會不斷添加。
我會在這里使用一個Counter
:
from collections import Counter
c = Counter()
for k, v in zip(x_list, y_list):
c[k] += v
嘗試這個:
dct = {}
x_list = (blue, orange, purple, green, yellow, green, blue)
y_list = (1, 2, 5, 2, 4, 3, 8)
for i in range(len(x_list)):
if x_list[i] in dct.keys():
dct[x_list[i]] += y_list[i]
else:
dct[x_list[i]] = y_list[i]
print dct
使用enumerate
函數的簡短解決方案:
x_list = ['blue', 'orange', 'purple', 'green', 'yellow', 'green', 'blue']
y_list = [1, 2, 5, 2, 4, 3, 8]
result = {}
for i, v in enumerate(x_list):
result[v] = y_list[i] if not result.get(v) else result[v] + y_list[i]
print(result)
輸出:
{'yellow': 4, 'orange': 2, 'blue': 9, 'green': 5, 'purple': 5}
試試這個代碼:
list_x =["apple", "mango", "orange", "apple","mango"]
list_y = [10,5,25,10,15]
total_dict = {}
for k, v in zip(list_x, list_y):
total_dict[k] = total_dict.get(k,0)+v
total_dict
的值最終為:
{'orange': 25, 'mango': 20, 'apple': 20}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.