我是 Python 新手,想为我的 csv 文件创建字典。我的数据格式如下:
c1 c2 p trade
GER USA 1 100
GER ITA 1 80
JPN ITA 2 120
USA GBR 1 70
DNK CAN 2 100
USA DNK 2 70
DNK GER 1 40
FRA GER 4 50
USA GER 6 80
我打算创建一个字典,它的键是国家(c1 和 c2),值是产品(p)。像这样:
dic_c1c2_products={"GER": 1, 4,6 "USA":1,2,6 "ITA": 1,2, "JPN": 2 "GBR":1, DNK:"2,1 "CAN":2 "FRA:4}
我写了下面的代码,但它不能正常工作:
rfile = open('filepath','r')
dic_c1c2_products = {}
for i in rfile :
lns = i.strip().split(',')
c1 = lns[0]
c2 = lns[1]
p = lns[2]
if not dic_c1c2_products.has_key(c1) and not dic_c1c2_products.has_key(c2):
dic_c1c2_products[c1] = [p,]
dic_c1c2_products[c2]=[p,]
elif dic_c1c2_products.has_key(c1) and not dic_c1c2_products.has_key(c2):
dic_c1c2_products[c2]=[p,]
if p not in dic_c1c2_products[c1]:
dic_c1c2_products[c1].append(p)
elif not dic_c1c2_products.has_key(c1) and dic_c1c2_products.has_key(c2):
dic_c1c2_products[c1] = [p,]
if p not in dic_c1c2_products[c2]:
dic_c1c2_products[c2].append(p)
elif dic_c1c2_products.has_key(c1) and dic_c1c2_products.has_key(c2):
if p not in dic_c1c2_products[c2] and dic_c1c2_products[c1]:
dic_c1c2_products[c1].append(p)
dic_c1c2_products[c2].append(p)
如有任何帮助,我们将不胜感激。
请您参考如下方法:
你可以使用 collections.defaultdict :
import csv
from collections import defaultdict
d= defaultdict(set)
with open('eggs.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
i,j,k=row[:3]
d[i].add(k)
d[j].add(k)
您只需要创建一个 defaultdict 并将 set 对象作为其值,然后遍历您的行并插入 1st 和 2nd 作为其键并将第三个元素添加到设定值。
