我尝试了几种方法从一个csv创建2个词典,或者创建一个包含三行输入的词典,但是输了,请看下面的代码。
import csv
vlan = open('vlan_dev.csv', 'rU')
readvlan = csv.reader(vlan)
lookup = open('lookup_table_dev.csv', 'rU')
readlookup = csv.reader(lookup)
assignment = open('assignment_dev.csv', 'rU')
readassignment = csv.reader(assignment)
outfile = open('testout.csv', 'w')
writer = csv.writer(outfile,)
used_header = False
for rows in readlookup:
#creating dictionary for lookup table
lookup_dict = {rows[0]:rows[4] for rows in readlookup}
#print lookup_dict
for rows in readassignment:
#creating dictionary for building assignment to department
assignment_dict = {rows[0]:rows[3]:rows[4] for rows in readassignment}
和
import csv
vlan = open('vlan_dev.csv', 'rU')
readvlan = csv.reader(vlan)
lookup = open('lookup_table_dev.csv', 'rU')
readlookup = csv.reader(lookup)
assignment = open('assignment_dev.csv', 'rU')
readassignment = csv.reader(assignment)
outfile = open('testout.csv', 'w')
writer = csv.writer(outfile,)
used_header = False
for rows in readlookup:
#creating dictionary for lookup table
lookup_dict = {rows[0]:rows[4] for rows in readlookup}
#print lookup_dict
for rows in readassignment:
#creating dictionary for building assignment to department
assignment_dict = {rows[0]:rows[3] for rows in readassignment}
#creating dictionary for floor assignment to department
department_dict = {rows[1]:rows[4] for rows in readassignment}
有更好的方法吗?
答案 0 :(得分:1)
尝试使用以下函数获取3个参数来创建字典。
import csv
foo_in = open('bar.csv', 'rU')
readfoo = csv.reader(foo_in)
for row in readfoo:
spam = row[0]
eggs = row[1]
foobar = row[2]
new_data = dict()
new_data.setdefault(spam, {})
new_data[spam].setdefault(eggs, []).append(foobar)
print new_data
这将为您提供使用3个项目的字典。