• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Занятие 1. Entering and output of data

Difficulty level:

Task«Unique orders»

💻 Python

The restaurant decided to find out the number of unique customers and how much each of them paid. Write a program that accepts a dictionary with customers and returns unique customers and their total costs in the institution.

Input format

The first line contains a single number of n & mdash; The number of transactions records. Each of the following n lines contains the name of the client (line without spaces) and the amount of purchase (an integer), separated by a gap.

Output format

One line containing the python dictionary, where the keys & mdash; These are unique customer names, and values ​​& mdash; Their total costs.

Example

Input

4
Peter 300
Anna 150
Peter 100
Anna 400

Output

{'Peter': 400, 'Anna': 550}

Hint

There will be no clue here, decide for yourself!

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Developer’s solution
# Инициализируем пустой словарь для хранения итоговых сумм по клиентам
client_totals = {}

# Считываем первое число - общее количество записей о покупках
try:
    num_records = int(input())

    # Проверяем, что количество записей не отрицательное
    if num_records < 0:
        # В случае отрицательного числа, считаем это некорректным вводом
        # и выводим пустой словарь, так как транзакций не будет.
        print({})
    else:
        # Запускаем цикл, который выполнится указанное количество раз
        for _ in range(num_records):
            # Считываем строку и разделяем ее на имя и сумму по пробелу
            # .split() по умолчанию разделяет по пробелам и возвращает список строк
            parts = input().split()
            name = parts[0]
            amount = int(parts[1])

            # Используем метод словаря get(). Он безопасен и удобен.
            # Если клиент (ключ 'name') уже есть в словаре, get() вернет его текущую сумму.
            # Если клиента еще нет, get() вернет значение по умолчанию, которое мы указали (0).
            # Затем к полученному значению мы прибавляем новую сумму и записываем результат в словарь.
            client_totals[name] = client_totals.get(name, 0) + amount

        # Выводим итоговый словарь с результатами
        print(client_totals)

except (ValueError, IndexError):
    # Эта часть кода сработает, если ввод некорректен.
    # Например, если вместо числа введено слово, или в строке с транзакцией нет суммы.
    # В таких случаях программа выведет пустой словарь, что является логичным
    # поведением при невозможности обработать данные.
    print({})

🎉 Congratulations! 🎉

You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

AD

Advertisement

red-snake blue-snake green-snake

Running your code...

Помощник ИИ

Привет! Я твой помощник по программированию. Задавай любые вопросы по Python, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!