0
對於下面數據,如何創建一個字典,id作爲元組[(X,Y)]創建字典從數據幀在Python
id x y
0 a 1 2
1 a 2 3
2 b 3 4
預期字典陣列的鍵和值是
{A:[(1,2),(2,3)],b:[(3,4)]}
對於下面數據,如何創建一個字典,id作爲元組[(X,Y)]創建字典從數據幀在Python
id x y
0 a 1 2
1 a 2 3
2 b 3 4
預期字典陣列的鍵和值是
{A:[(1,2),(2,3)],b:[(3,4)]}
當在桌子上進行迭代(但是你正在做的話)檢查是否該ID已經在dict
並附加到現有值或添加新密鑰:
data = {}
for id,x,y in SOURCE:
if id in data:
data[id].append((x,y))
else:
data[id] = [(x,y)]
通過@ tadhg - 麥當勞 - 延森提供的解決方案似乎需要defaultdict優勢的絕佳機會:
from collections import defaultdict
data = defaultdict(list)
with open(SOURCE_FILE_NAME) as source:
for line in source:
id, x, y = line.rstrip().split()
data[id].append((x, y))
這就避免了決定來設置或追加 - 只需追加,讓defaultdict做對你來說是正確的。
可能是http://stackoverflow.com/questions/26367812/appending-to-list-in-python-dictionary –