2017-03-16 77 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]

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