return items from dictionary not as tuple
Question:
I have an excel file and I accumulate thre values for each fruit sort with each other.
So I do it like this:
def calulate_total_fruit_NorthMidSouth():
import openpyxl
import tabula
excelWorkbook = openpyxl.load_workbook(path, data_only=True)
sheet_factuur = excelWorkbook['Facturen ']
new_list =[]
fruit_sums = {
'ananas': 0,
'apple': 0,
'waspeen': 0,
}
fruit_name_rows = {
'ananas': [6, 7, 8],
'apple': [9, 10, 11],
'waspeen': [12, 13, 14],
}
array = [row for row in sheet_factuur.values] # type: ignore
# excel does not have a row 0
for row_num, row_values in enumerate(array, 1):
for fruit in ['ananas', 'apple', 'waspeen']: # loop through specific fruits
if row_num in fruit_name_rows[fruit]:
# index 4 is column 5 in excel
fruit_sums[fruit] += row_values[4] # type: ignore
return list(fruit_sums.items())
But the output is this:
[('ananas', 3962), ('apple', 3304.08), ('waspeen', 3767.3999999999996)]
But the output has to look like this:
ananas 3962
apple 3304.08
waspeen 3767.39
How to archive this with return statement?
Answers:
Not sure if this is the best way to solve this problem but you could add this to your code before printing:
mylist = list(fruit_sums.items())
for i in mylist:
newlist = list(i)
for x in range(len(newlist)):
newlist[x] = str(newlist[x])
print(" ".join(newlist))
Try something like this:
def f():
x = {'a': 1, 'b': 2, 'c': 3}
return 'n'.join(f'{a} {b}' for a, b in x.items())
print(f())
# a 1
# b 2
# c 3
I have an excel file and I accumulate thre values for each fruit sort with each other.
So I do it like this:
def calulate_total_fruit_NorthMidSouth():
import openpyxl
import tabula
excelWorkbook = openpyxl.load_workbook(path, data_only=True)
sheet_factuur = excelWorkbook['Facturen ']
new_list =[]
fruit_sums = {
'ananas': 0,
'apple': 0,
'waspeen': 0,
}
fruit_name_rows = {
'ananas': [6, 7, 8],
'apple': [9, 10, 11],
'waspeen': [12, 13, 14],
}
array = [row for row in sheet_factuur.values] # type: ignore
# excel does not have a row 0
for row_num, row_values in enumerate(array, 1):
for fruit in ['ananas', 'apple', 'waspeen']: # loop through specific fruits
if row_num in fruit_name_rows[fruit]:
# index 4 is column 5 in excel
fruit_sums[fruit] += row_values[4] # type: ignore
return list(fruit_sums.items())
But the output is this:
[('ananas', 3962), ('apple', 3304.08), ('waspeen', 3767.3999999999996)]
But the output has to look like this:
ananas 3962
apple 3304.08
waspeen 3767.39
How to archive this with return statement?
Not sure if this is the best way to solve this problem but you could add this to your code before printing:
mylist = list(fruit_sums.items())
for i in mylist:
newlist = list(i)
for x in range(len(newlist)):
newlist[x] = str(newlist[x])
print(" ".join(newlist))
Try something like this:
def f():
x = {'a': 1, 'b': 2, 'c': 3}
return 'n'.join(f'{a} {b}' for a, b in x.items())
print(f())
# a 1
# b 2
# c 3