问题
I open a file that contains this:
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
and I want a dictionary like:
{'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}}
I have tried this:
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])
The problem is I dont know how to add the price of product "cereal" at barakobama's value.
回答1:
Try this:
#!/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)
Output:
{'vladimirputin': {'milk': '2.87', 'bread': '0.66', 'parsley': '1.33'}, 'barakobama': {'parsley': '0.76', 'cereal': '3.22'}}
If you want float
s, change the line to:
d[fields[2]] = dict((item.split(":")[0], float(item.split(":")[1])) for item in fields[3].split(","))
Output:
{'vladimirputin': {'milk': 2.87, 'parsley': 1.33, 'bread': 0.66}, 'barakobama': {'parsley': 0.76, 'cereal': 3.22}}
来源:https://stackoverflow.com/questions/23240008/how-to-make-string-to-dictionary-and-update-values-that-exist