字典附加在Python中

时间:2014-06-05 14:45:39

标签: python dictionary append

现在,当我需要所有行时,data和filenameVariable正在打印最后一行。我试过.append但是没有用。我还能用什么?

以下是我正在使用的数据:

    someCSVfile.csv|cust_no,0|streetaddr,1|city,2|state,3|zip,4|phone_home,5|firstname,6|lastname,7|status,9|
    someCSVfile1.csv|cust_no,0|streetaddr,1|city,2|state,3|zip,4|phone_home,5|firstname,6|lastname,7|status,9|

到目前为止,这里是代码:

import csv
reader = csv.reader(open('match_log.txt','rb'), dialect='excel', delimiter='|')

data = {}

for row in reader:
  filenameVariable = row[0] 
  data = dict(item.split(',') for item in row[1:])

print data
print filenameVariable

#right now its taking the final row. I need all rows

1 个答案:

答案 0 :(得分:0)

问题是您正在覆盖CSV中的每一行data。相反,您需要做的就是将row[0]作为data字典中的关键字:

import csv
reader = csv.reader(open('match_log.txt','rb'), dialect='excel', delimiter='|')

filenameVariable = []
data = {}

for row in reader:
  filenameVariable.append(row[0])
  data[row[0]] = dict(item.split(',') for item in row[1:])

print data
print filenameVariable