簡體   English   中英

如何訪問列出的詞典中列表中的項目。

[英]How to access an item in a list within a listed dictionary.

我目前有很多客戶數據,其中每一行數據都是客戶的單獨交互,但是某些客戶進行了多次交互,因此許多客戶有多行。 每個多重互動客戶行中的某些變量相同,而其他變量則不同(即年齡可能相同,但是商店不同)。

我試圖創建一個字典,其中客戶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

注意,我很確定我不能使用item [1 [7]]來引用列表中的第一個列表,然后引用第七個項目,但是我也不想迭代每個項目的每個內部字典列表。 我遇到了一系列不同的錯誤,真的不知道如何繼續。

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

假設您的字典看起來像這樣:

customer_dict =

{“ cust_id_1”:[[item1],[item2,item3],[item4,item5]],

“ cust_id_2”:[[item7],[item8],[item9,item10,item11]]}

為了訪問item4,您可以使用customer_dict [“ cust_id1”] [2] [0]

希望我正確了預定的詞典。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM