我打开一个包含以下内容的文件:
TransactionNo Date CustomerId PurchasePairs
------------- ---- ---------- -------------
1 09-04-2014 barakobama potatoes:2.67,sugar:1.98,cereal:5.99,crisps:1.09
2 11-04-2014 barakobama parsley:0.76,cereal:3.22
3 11-04-2014 vladimirputin bread:0.66,milk:2.87,parsley:1.33
我想要一本像这样的字典
{'vladimirputin': {'milk': 2.87, 'parsley': 1.33, 'bread': 0.66},
'barakobama': {'parsley': 0.76, 'sugar': 1.98, 'crisps': 1.09,
'potatoes': 2.67, 'cereal': 9.21}}
我试过这个:
def makeCustomerDictionary(fileNameStr):
my_dict={}
file=open(fileNameStr,'r')
for line in file:
if line.isdigit():
line_split=line.split("t")
customer_key=set(line_split[2])
问题是,我不知道如何将产品"谷物"的价格加在巴拉科巴马的价值上。
试试这个:
#!/usr/bin/env python3
d = {}
with open("in.txt") as i:
header1 = i.readline()
header2 = i.readline()
for line in i:
fields = line.split()
d[fields[2]] = dict(item.split(":") for item in fields[3].split(","))
print(d)
输出:
{'vladimirputin': {'milk': '2.87', 'bread': '0.66', 'parsley': '1.33'}, 'barakobama': {'parsley': '0.76', 'cereal': '3.22'}}
如果您想要float
s,请将行更改为:
d[fields[2]] = dict((item.split(":")[0], float(item.split(":")[1])) for item in fields[3].split(","))
输出:
{'vladimirputin': {'milk': 2.87, 'parsley': 1.33, 'bread': 0.66}, 'barakobama': {'parsley': 0.76, 'cereal': 3.22}}