2017-03-16 100 views
0

我目前有很多客戶數據,其中每行數據都是客戶的個人交互,但是有些客戶有多次交互,因此許多客戶有多行。多交互客戶行中的每個變量都是相同的,而其他變量是不同的(即年齡可能相同,但不同的商店)。如何訪問列表字典中列表中的項目。

我試圖創建一個字典,其中客戶ID是鍵,行數據附加到ID。這意味着附加到每個鍵是列表的列表。因此,我試圖從基於每個獨特客戶的第一次交互中訪問來自一系列不同交互的項目(單個變量)。

import sys 
import re 
import csv 
from collections import defaultdict 


def extract_data(filename): 
    customer_list = {} 
    count = 0 
    counter = 1 
    file = open(filename, 'r') 
    reader = csv.reader(file, delimiter=',') 
    for row in reader: 
    if row[2] not in customer_list: 
     customer_list[row[2]] = [row] 
     count += 1 
    else: 
     customer_list[row[2]].append(row) 

    print 'total number of customers: ', len(customer_list.keys()) 

    zipcodes = [] 
    numzips = 0 
    for customer in customer_list: 
    for item in customer.value(): 
     if item[1[7]] not in zipcodes: 
     zipcodes.append(item[1[7]]) 
     numzips += 1 
    print zipcodes 
    print numzips 

注意我敢肯定,我不能使用項目[1 [7]引用列表中的第一個列表,然後第7項,但我也不想遍歷每個內每個項目的詞典列表。我遇到了一系列不同的錯誤,真的不知道如何繼續。

任何幫助/建議將不勝感激。

+0

請分享樣本數據,這樣很容易理解。 – Hackaholic

回答

0

假設你的詞典看起來是這樣的:

customer_dict =

{ 「cust_id_1」:[物品1],[項目2,項目3],[ITEM4,ITEM5],

「cust_id_2」:[[item7],[item8],[item9,item10,第11項]] }

爲了訪問ITEM4,可以使用customer_dict [ 「cust_id1」] [2] [0]

希望我能找到正確的字典。

相關問題