I get an error when i run this code
cost = float(prices[strs[0]][0])
TypeError: float() argument must be a string or a number, not 'list'
i dont know how to fix the error
prices = {}
groceries = []
file = open("grocery_store_price_list.txt", "r")
for strx in file:
strs = list(filter(None, strx.strip().split(" ")))
prices[strs[0]] = [strs[1]], [strs[2]]
file.close()
file = open("my_personal_gro_list.txt", "r")
for strx in file :
strs = list(filter(None, strx.strip().split(" ")))
groceries.append([strs[1], strs[0]])
headings = "{:15s} {:3s} {:10s} {:5s} {:6s}".format("item", "qty", "unit",
"cost", "total")
print(headings)
finalCost = 0
for strs in groceries
item = strs[0]
qty = int(strs[1])
unit = prices[strs[0]][1]
cost = float(prices[strs[0]][0])
prices[strs[0]][0] is a list that contains two prices. So you'll want to cast both values separately or using cost = [float(v) for v in prices[strs[0]][0]].
prices = {}
groceries = []
file = open("grocery_store_price_list.txt", "r")
for strx in file:
strs = list(filter(None, strx.strip().split(" ")))
prices[strs[0]] = [strs[1]], [strs[2]] # List of two prices, why you get the error.
file.close()
file = open("my_personal_gro_list.txt", "r")
for strx in file :
strs = list(filter(None, strx.strip().split(" ")))
groceries.append([strs[1], strs[0]])
headings = "{:15s} {:3s} {:10s} {:5s} {:6s}".format("item", "qty", "unit",
"cost", "total")
print(headings)
finalCost = 0
for strs in groceries
item = strs[0]
qty = int(strs[1])
unit = prices[strs[0]][1]
cost = [float(v) for v in prices[strs[0]][0]]
# OR cost = [float(prices[strs[0]][0][0]), float(prices[strs[0]][0][1])]
>>> prices = {}
>>> prices['a'] = [1], [2]
>>> prices
{'a': ([1], [2])}
Taking above as an example, your prices contains a tuple and each is a list that contains 1 element
prices[strs[0]] = [strs[1]], [strs[2]]
You either apply float() on one of the values or modify your prices let each key has one value
Related
The loadInventory function with a string filename as parameter reads the contents from inventory.txt
def loadInventory(filename):
inventory = {}
inventoryFile = open(filename)
for line in inventoryFile:
itemID,itemStock = line.split(":")
inventory[itemID] = itemStock
inventory = {itemID: itemStock for itemID, itemStock in inventory.items()}
inventory[itemID] = [itemStock.replace('\n', '')]
# print(f"{inventory}")
return inventory
def main():
print(loadInventory('Inventory.txt'))
main()
Inventory.txt:
C05:10,10,5,4
C01:0,20,10,5
C11:10,20,10,1
C03:0,0,10,0
C10:1,1,1,1
Output:
{'C05': ['10,10,5,4'], 'C01': ['0,20,10,5'], 'C11': ['10,20,10,1'], 'C03': ['0,0,10,0'], 'C10': ['1,1,1,1']}
Intended Output:
{'C05':[10,10,5,4], 'C01':[0,20,10,5], 'C11':[10,20,10,1],
'C03':[0,0,10,0]}
Try replacing this line:
inventory[itemID] = [itemStock.replace('\n', '')]
To:
inventory[itemID] = [int(i) for i in itemStock.replace('\n', '').split(',')]
Or:
inventory[itemID] = list(map(int, itemStock.replace('\n', '').split(',')]))
This the link to see the image of the text file I need help with feature one, click here to see the imageFor some reason when I print out the average of the list, it only shows the number from the text file. I don't know where my mistake is. I think the issue might be when am appending the list.
f = open("votes.txt")
lines = f.read().split('\n')
issueA = {}
voteAa = {}
voteBa = {}
while(True):
for line in lines:
col = line.split(' ')
issue = col[0]
voteA = float(col[1])
voteB = float(col[2])
if voteA in voteAa:
voteAa[issue].append(voteA)
else:
voteAa[issue] = [voteA]
if voteB in voteBa:
voteBa[issue].append(voteB)
else:
voteBa[issue] = [voteB]
choice = int(input("Which choice? "))
if choice == 1:
for issue in voteAa:
sumVote = sum(voteAa[issue])
avg = sumVote / len(voteAa[issue])
print("avg is ",sumVote)
how about this
f = open("votes.txt")
lines = f.read().split('\n')
issues = []
voteAa = []
voteBa = []
for line in lines:
col = line.split(' ')
issue = col[0]
voteA = float(col[1])
voteB = float(col[2])
issues.append(issue)
voteAa.append(voteA)
voteBa.append(voteB)
avgA = voteAa.count(0)/len(issues) * 1.0
avgB = voteBa.count(0)/len(issues) * 1.0
if (avgA > avgB):
print('B higher than A'
elif (avgB > avbA):
print('A higher than B')
Since you need average by issue
remove for issue loop
and compute average in one line with special mean function like below
avg = mean(voteAa.values())
or, if you prefer keep it close to your code
sumVote = sum(voteAa.values())
avg = sumVote / len(voteAa)
also correct print line to
print("avg is ", avg)
Also you should just collect votes not need for if in the first loop.
So resulting script is
f = open("votes.txt")
lines = f.read().split('\n')
issueA = {}
voteAa = {}
voteBa = {}
for line in lines:
col = line.split()
issue = col[0]
voteA = float(col[1])
voteB = float(col[2])
voteAa[issue] = voteA
sumVote = sum(voteAa.values())
avg = sumVote / len(voteAa)
print("avg is ", avg)
I tried to keep close to your original code, and did not say replace dictionaries with arrays, it could be simplified even further if you like, say with pandas or even standard https://docs.python.org/3/library/csv.html
I do not know why some items are not formatted right, the short names seem to be fine but the longer ones throw themselfs off
https://pastebin.com/pkGL0Nwy
prices = {}
groceries = []
file = open("grocery_store_price_list.txt", "r")
for strx in file:
strs = list(filter(None, strx.strip().split(" ")))
prices[strs[0]] = [strs[1]], [strs[2]]
file.close()
file = open("my_personal_gro_list.txt", "r")
for strx in file :
strs = list(filter(None, strx.strip().split(" ")))
groceries.append([strs[1], strs[0]])
headings = "{:6s} {:9s} {:6s} {:7s} {:6s}".format("item", "qty", "unit", "cost", "total")
print(headings)
finalCost = 0
for strs in groceries:
item = strs[0]
qty = int(strs[1])
unit = prices[strs[0]][1]
cost = float(prices[strs[0]][0][0])
total = qty*cost
finalCost += total
print(item, qty, unit, cost, total,)
print("{item}\t{qty}\t{unit}\t{cost}\t{total}".format(item=item, qty=qty, unit=unit, cost=cost, total=total))
I have 2 text files that look like the ones below:
input.txt
shoes
memory card
memory card
input1.txt
shoes
shoes
i want to store the data in a dictionary query will be my key. and count will be my value.input.txt and input1.txt is my two input.in the format word : [count of word in input.txt,count of word in input1.txt]
like below:-
op:-
shoes:[1,2]
memory card:[2,0]
Here is my approach with normal loops:
i = 'shoes\nmemory card\nmemory card'
i2 = 'shoes\nshoes'
dict = {}
i = i.split('\n')
i2 = i2.split('\n')
for ele in i:
if ele not in dict:
dict[ele] = [1,0]
else:
dict[ele][0] +=1
for ele in i2:
if ele not in dict:
dict[ele] = [0,1]
else:
dict[ele][1] +=1
print dict
You could do as follows:
from collections import Counter
with open('input.txt', 'r') as f:
lines1 = [l.strip() for l in f]
with open('input1.txt', 'r') as f:
lines2 = [l.strip() for l in f]
# count the number of occurrences of your words in each file
c1 = Counter(lines1)
c2 = Counter(lines2)
out_dict = {}
# for each unqiue word from both files,
#put its count int the out_dict.
for k in set(c1) | set(c2) :
out_dict[k] = [c1.get(k,0), c2.get(k,0)]
print(out_dict)
The result is:
{'shoes': [1, 2], 'memory card': [2, 0]}
actually i am getting data from some json file.
import os
import json
auto_prefix = u'\u200B'
path1 = "/home/mine/new-log/1-search-logs-01-20/"
dict = {}
for path,dirs,files in os.walk(path1):
for data in files:
with open("/home/mine/new-log/1-search-logs-01-20/"+data) as text:
for line in text:
file2 = json.loads(line)
try:
query = (file2["appData"]["_request_params"]["params"]["q"])[0]
if auto_prefix in query:
query = query.replace(auto_prefix,"")
query = query.encode('utf-8').lower()
if query not in dict:
dict[query] = [1,0]
else:
dict[query][0] += 1
else:
query = query.encode('utf-8').lower()
if query not in dict:
dict[query] = [0,1]
else:
dict[query][1] += 1
except KeyError:
pass
print dict
I have a problem. I'm trying to print a serie of lists in python to have it with a vertical align. My code is:
def show():
book = "data.txt"
f = open(book,'r')
line = f.readlines()
f.close()
x=0
z = ''
l = []
x = []
i = 0
starting = '{:>4} {:>15} {:>15}'.format('Name', "Gender", "Year")
print(starting)
for p in line:
p = p.replace(',',' ')
x = p.index(' ')
name = p[0:x]
a = p.index('e 1')
gender = p[x:a+1]
year = p[(a+2):]
if len(name) == 3:
line_new = '{:>2} {:>15} {:>15}'.format(name, gender, year)
else:
line_new = '{:>5} {:>15} {:>15}'.format(name, gender, year)
print(line_new)
The problem is that I'm trying to have something like:
I want to put all the names of the left (and I don't have problems) then, under Gender, I want to create an equal list of Genders all on the same vertical and same thing for year
Untested, but try this:
import itertools
with open("data.txt") as data:
pep = [line.strip().split(',') for line in data]
widths = [len(max(r, key=len)) for r in itertools.izip_longest(*pep, fillvalue="")]
print "%-{0}%s%-{1}%s%-{2}%s".format(widths[0], widths[1], widths[2])\
%("Name", "Gender", "Year")
print "\n".join(["%-{0}%s%-{1}%s%-{2}%s".format(widths[0], widths[1], widths[2])\
%(attr[0], attr[1], attr[2]) for attr in pep])