在不使用defaultdict的情況下最簡單的方法是什麼?如果使用核心python功能執行此操作太麻煩,那麼defaultdict可以。向字典中的相同鍵添加多個不同值的列表
我有一個鍵列表作爲列表。
我有一個短循環來創建一些值的列表,其中我想映射到字典中的鍵。
所以,最後我會得到每個鍵的多個值。然後打印。
這是我迄今爲止...
Keys = ['A','B','C'] #the keys that will be mapped to all values start here in a list
Values = [] #starting with empty values
Dict = dict(zip(Keys, Values)) #starting with a dict of keys mapped to empty values
x=0
while x < 5:
x += 1
MoreValues = [1+x,2+x,3] #adding x only to give some different values
Dict = dict(zip(Keys, MoreValues))
print Dict
輸出與此代碼是:
{'A': 2, 'C': 3, 'B': 3}
{'A': 3, 'C': 3, 'B': 4}
{'A': 4, 'C': 3, 'B': 5}
{'A': 5, 'C': 3, 'B': 6}
{'A': 6, 'C': 3, 'B': 7}
另一種方式來看待這個問題,是如何得到的這些字典合併所以A,B,C的鍵被映射到這些多個值,給定該循環以生成值列表。
輸出應該是:
{'A': [2, 3, 4, 5, 6], 'C': [3, 3, 3, 3, 3], 'B': [3, 4, 5, 6, 7]}
爲什麼你不想使用defaultdict? – karthikr 2014-09-21 22:07:41
我想看看如何通過核心python功能來做到這一點,但如果它太麻煩,那麼defaultdict就沒關係。 – Steve 2014-09-21 22:10:37
這裏有幾種方法:http://stackoverflow.com/questions/5946236/how-to-merge-multiple-dicts-with-same-key – karthikr 2014-09-21 22:13:34