Reputation: 11
I had this current text file as inventory.txt
<br>C01:10,10,5,4</br>
<br>C02:0,20,10,5</br>
<br>C03:10,20,10,1</br>
<br>C04:0,0,10,0</br>
<br>C5:1,1,1,1</br>
I would like to use python to read my file and using a dictionary and lists to populate the output as below.
{'C01':[10, 10, 5, 4], 'C02':[0, 20, 10, 5], 'C03':[10, 20, 10, 1], 'C04':[0, 0, 10, 0], 'C05:[1, 1, 1, 1]}
This is my code so far:
for line in file:
item , stock = line.split(":")
a = stock.strip().split(",")
b = item
c = stock
num1, num2, num3, num4 = stock.strip().split(",")
#print(a) #print ['10', '10', '5', '4']
#print(b) #print C01
#print(c) #print 10, 10, 5, 4
storeNumber[item] = [str(num1), str(num2), str(num3), str(num4)]
print(storeWord[item])
But this is not producing the desired output.
Upvotes: 0
Views: 109
Reputation: 23166
Try:
storeNumber = dict()
with open("inventory.txt") as f:
for line in f:
item, stock = line.strip().split(":")
storeNumber[item] = [int(i) for i in stock.split(",")]
Upvotes: 1
Reputation: 21239
You're not far off:
dx = {
key: [int(i) for i in value.strip().split(",")]
for key, value in ((l.split(":")[0], l.split(":")[1]) for l in file)
}
All this does is use a dictionary comprehension to assign to each key the split-out list for each line. The internal generator (((l.split..., ...) for l in file)
) takes each line of the file and turns it into a tuple of the first and second elements of a split on the :
character. Being a generator, it's not called immediately, only when the dictionary comprehension passes over it.
The dictionary comprehension takes the first value of the tuple (the key) and assigns it as the dictionary key, and then takes the value, splits it on ,
. This naturally produces a list, which can be iterated over to produce ints for each element if desired using a for-comprehension.
>>> file = [
... "C01:10,10,5,4",
... "C02:0,20,10,5",
... "C03:10,20,10,1",
... "C04:0,0,10,0"]
>>> dx = {
... key: [int(i) for i in value.strip().split(",")]
... for key, value in ((l.split(":")[0], l.split(":")[1]) for l in file)
... }
>>> dx
{'C01': [10, 10, 5, 4], 'C02': [0, 20, 10, 5], 'C03': [10, 20, 10, 1], 'C04': [0, 0, 10, 0]}
Upvotes: 2
Reputation: 3
You can add this code to the end of the for loop:
storeNumber.update({b:a})
Upvotes: 0
Reputation: 4843
You can do it with a quick loop like so. Note that this assumes your data is all valid and formatted correctly. :
f = open('file.txt')
output_dict = {}
for line in f:
line = line.rstrip()
if len(line) > 0:
split_line = line.split(':')
output_dict[split_line[0]] = [int(x) for x in split_line[1].split(',')]
f.close()
Upvotes: 1