2015-12-30 31 views
0
使用defaultdict上線

我interrating通過JSON的線,並試圖創造所有以獨特的playerID發生事件的解釋,但我不斷收到錯誤AttributeError: 'collections.defaultdict' object has no attribute 'append'嘗試在JSON

我正在使用的代碼如下:

import json, csv, sys 
from collections import defaultdict, Counter 
lastTimeByPlayer = defaultdict(int) 
uniquePlayerID = defaultdict(list) 
lasttime = 0 
totalCircuits = 0 
playerID = 0 

allCircuitsByUniquePlayerID = defaultdict(lambda : defaultdict(int)) 

for line in infile: 
datum = json.loads(line) 
time = int(datum['timestamp']) 
try: 
    pids = list(datum['playspace_ids']) 
except: 
    pids = [] 
for player in pids: 
    if (time - lastTimeByPlayer[player]) > int(sys.argv[1]): #sys args is a set interval "dead time" interval that indicates a new player has arrived 
     playerID = playerID +1 
     uniquePlayerID[player].append(playerID) 
    lastTimeByPlayer[player] = time 
    if datum['key'] == "MakeCircuitCreated": 
     allCircuitsByUniquePlayerID[playerID].append(time) 

我覺得它是與我在如何創建allCircuitsByUniquePlayerID[playerID]鍵的每個實例,但我真的不知道。在此先感謝

+0

由於erorr是allCircuitsByUniquePlayerID,你不應該表明是如何定義的? –

+0

抱歉錯過了,當我在複製代碼 – Mike

+2

OK,讓字典的每個元素本身就是一個defaultdict。那麼爲什麼你使用'append'?你期望發生什麼? –

回答

0

我只是猜測你的意圖,但我認爲你要麼想:

allCircuitsByUniquePlayerID = defaultdict(list) 

,或者你缺少某種電路ID和你想要的東西,如:

 allCircuitsByUniquePlayerID[playerID][circuitID].append(time) 
+0

有點像第二個(正如我上面解釋的那樣) - 我實際上需要在每個ID的字典中​​存儲幾個東西(如果事件「MakeCircuitCreated」發生該ID),所以最終我想要的是類似[ID1,{[時間1,屬性],[時間2,屬性] ... [天美時,屬性],[ID2,[...],[IDX,[...] - 現在我只是試圖讓第一部分工作(不知道這是否清除它) – Mike