Невозможно напечатать несколько ключей разных словарей в Python - PullRequest
0 голосов
/ 06 апреля 2020

Я хочу напечатать несколько ключей из разных словарей в списке. Мой словарь получается правильным с правильными элементами, но когда я пытаюсь отформатировать окончательный оператор печати, он просто печатает последний ввод. Это не сохраняет локальные переменные. И я довольно заблудился от того, как сделать общий итог, так как он включает локальные переменные.

Вот мой код:

#making the list
grocery_history = []

#assign grand total variable
grand_total = 0

#definition of the input sequence
def questions():

    #creating the individual dictionary for each item
    current_item = {}

    #assigning the item name keys
    print("Item name:")
    item_name = input()
    current_item['name'] = item_name

    #assigning the quantity keys
    print("Quantity purchased:")
    quantity = input()
    current_item['number'] = quantity

    #assigning the cost keys
    print("Price per item:")
    cost = input()
    current_item['price'] = cost

    #calculating the item total and assigning its' key
    item_total = float(quantity) * float(cost)
    current_item['item_total'] = item_total

    #input option to continue
    print("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")
    choice = input()

    #adding dictionary to list
    grocery_history.append(current_item)

    #defining the final formating
    def final_string():
        print(str(current_item['number']) + " " + str(current_item['name']) +  " @   $" + str(current_item['price']) + " ea   $" + str(current_item["item_total"]))

    #option to continue
    if choice == "c":
        questions()

    #option to print summary
    elif choice == "q":
        #### I think this is where my problem is
        for i in range(len(grocery_history)):
            final_string()
        ## not sure if this is how to calculate grand total
        for x in range (len(grocery_history)):
            x = item_total
            grand_total = item_total + x

    print("Grand total: $" + str(grand_total))


#call questions function
questions()

Ответы [ 3 ]

0 голосов
/ 06 апреля 2020

Извините, но это очень странный способ написания этого кода. На самом деле, вы можете сделать это сложнее для себя, чем на самом деле. Я переделал это намного проще:

groceries = []

shopping = True

while shopping:
    item = {
        "Name":input("Name:\n"),
        "Quantity":float(input("Quantity:\n")),
        "PricePerItem":float(input("Price Per Item:\n"))
        }
    groceries.append(item)
    if "n" == input("Continue?(y/n) ").lower():
        shopping = False

total = 0
for item in groceries:
    total += item["Quantity"] * item["PricePerItem"]
    print(item["Name"]+" - Quantity: "+str(item["Quantity"])+" Price Per Item: $"+str(item["PricePerItem"])+" Current Total: $"+str(total)+"\n")

print("Grand Total: $"+str(total))

Это даст вам вывод, подобный этому: enter image description here

0 голосов
/ 06 апреля 2020

Ваша функция должна получить элемент, который должен распечатать как параметр. Я использовал f-строку для форматирования вывода. Это намного приятнее, чем конкатенация строк вручную.

def final_string(item):
    print(f"{item['number']} {item['name']} @   ${item['price']} ea   ${item['item_total']}")

Кстати, функция final_string должна быть определена на верхнем уровне, а не в функции questions.

Теперь вам нужно добавьте параметр, где вы вызываете функцию.

for i in range(len(grocery_history)):
    final_string(grocery_history[i])

Но использование диапазона по длине итерируемого для доступа к отдельным элементам не очень pythoni c и более сложный, чем это должно быть. Итерируемый (как список) ... итерируемый. Поэтому измените этот код на:

for item in grocery_history:
    final_string(item)

Чтобы вычислить общий итог, вы должны сложить сумму для каждого элемента. Поскольку ваш элемент представляет собой словарь, а общее количество элементов представляет собой значение записи с ключом 'item_total', вам необходимо добавить эти значения.

grand_total = 0
for item in grocery_history:
    grand_total += item['item_total']

Или как один вкладыш, используя sum и генератор.

grand_total = sum(item['item_total'] for item in grocery_history)
0 голосов
/ 06 апреля 2020

Проблема в том, что вам нужен параметр для final_string(). В противном случае он будет только печатать значение current_item.

Я бы вытащил окончательную строковую функцию следующим образом

def final_string(item):
    print(str(item['number']) + " " + str(item['name']) +  " @   $" + str(item['price']) + " ea   $" + str(item["item_total"]))

Затем изменил бы ваш код соответственно

#option to print summary
elif choice == "q":
    for item in grocery_history:
        final_string(item)
    grand_total = sum([item['item_total'] for item in grocery_history])
...