• 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
  • к

Занятие 8. Dictionary

Difficulty level:

Task«Bookstore sales analysis»

You work in a bookstore and are responsible for the analysis of sales. You need to process data on the sales of books for a month and prepare a report that will help to understand which books are in greatest demand and which authors bring the greatest income.

Input format

first the integer is introduced & nbsp; n & nbsp;-the number of sales records. Style = "Text-align: Justify;"> then enters & nbsp; n & nbsp; lines, each in the format: & nbsp; "name_Knigi The number of_-dummy_ sequences Price ", where:
rn
name & nbsp;-- Line, name of the book (without gaps).
rn
author & nbsp;-line, name of the author (without gaps).
rn
number of_prozen_ sectors & nbsp;-the whole number sold, the number of copies sold by this Books. RN
price -a material number, the price of one copy of the book

Output format

the program should be withdrawn:
rn
1) the name of the most popular book (books with the largest number of copies sold).
rn
2) the name of the author, the name of the author, the name of the author, the name of the author, the name of the author, the name of the author, the name brought the greatest revenue.
rn
3) the average price of all books sold (with an accuracy of a comma)

Example

Input

3
Voymir Levtolstoy 10 300.00
Crime announcement Fedordostoevsky 5 450.50
Masters Mikhailbulgakov 7 400.00

Output

The most popular book: Voymir
Author with the greatest revenue: Levtolstoy
Average price: 368.58

Hint

Useful methods for working with dictionaries in Python

Dictionaries are one of the most powerful and flexible data structures in Python. To use them effectively, it is important to know the basic methods. Let's take a closer look at them.

The keys() method

Returns all dictionary keys as a special representation object dict_keys.

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
keys = my_dict.keys()
print(keys)  # Output: dict_keys(['key1', 'key2', 'key3'])

A useful tip: The dict_keys object is iterable, meaning you can use it in a for loop. However, this is not a list. If you need a list of keys (for example, for index access), simply convert it using the list() function.

key_list = list(my_dict.keys())
print(key_list[0]) # Output: key1

The values() method

Returns all dictionary values as a representation object dict_values.

values = my_dict.values()
print(values) # Output: dict_values(['value1', 'value2', 'value3'])

A useful tip: Like dict_keys, dict_values can be iterated, but it is not a list. The conversion to list() also works if you need a list of values. This is convenient, for example, to check for the presence of a value.

The items() method

Returns all key-value pairs as a dict_items object, where each pair is represented as a tuple.

items = my_dict.items()
print(items) # Output: dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

A useful tip: This method is incredibly convenient for iterating through a dictionary when you need both a key and a value at the same time. This is considered the most "Pythonic" way to bypass the dictionary.

for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")

get() method

Returns the value by key. If there is no key, it returns the default value (or None if it is not specified).

value = my_dict.get("key1")
print(value) # Output: value1

value_nonexistent = my_dict.get("key4", "there is no such key")
print(value_nonexistent) # Output: there is no such key

A useful tip: Use get() instead of direct access through square brackets (my_dict["key4"]) when you are not sure if the key exists in the dictionary. This will avoid the KeyError error and the crash of the program. This is much safer when working with data that comes from external sources.

The popitem() method

Deletes and returns the last added key-value pair as a tuple.

last_item = my_dict.popitem()
print(last_item) # Output: ('key3', 'value3')
print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2'}

A useful tip: This method works according to the LIFO (Last-In, First-Out) principle. It is useful when you need to process dictionary elements in the reverse order of their addition. (Guaranteed LIFO order is supported in Python 3.7+).

The update() method

Updates the dictionary by adding key-value pairs from another dictionary or from an iterable object with pairs.

# The original my_dict dictionary is already without 'key3'
my_dict.update({"key4": "value4", "key1": "new value1"})
print(my_dict)
# Output: {'key1': 'new value1', 'key2': 'value2', 'key4': 'value4'}

A useful tip: Note that if the key from the updating dictionary already exists in the original one, its value will be overwritten. update() is an effective way to merge two dictionaries.

Nested dictionaries

Dictionaries can contain other dictionaries as values. This allows you to create complex hierarchical data structures very similar to the JSON format.

nested_dict = {
    "key1": {"plugg1": "value1"},
"key2": {"plugg2": "value2"}
}

# Accessing the nested value
print(nested_dict["key1"]["plugg1"]) # Output: value1

An example of a multidimensional structure in dictionaries

students = {
    "Alice": {"age": 25, "grades": [88, 92, 85]},
    "Bob": {"age": 22, "grades": [79, 85, 80]},
    "Charlie": {"age": 23, "grades": [90, 87, 85]}
}

# Getting Alice's age
print(students["Alice"]["age"]) # Output: 25

# Getting the first grade Bob
print(students["Bob"]["grades"][0]) # Output: 79

# Adding a new student
students["David"] = {"age": 24, "grades": [82, 79, 88]}
print(students)

A useful tip: When working with nested dictionaries, the risk of getting a KeyError increases. For secure access to the embedded data, you can use a chain of calls get().

# Safely obtaining the age of a student, which may not be
age = students.get("Eve", {}).get("age", "Unknown")
print(age) # Output: Unknown

Here students.get("Eve", {}) will return an empty dictionary {}, since there is no student "Eve", and already this empty dictionary will be called .get("age", ...), which will prevent the error.

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

🎉 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, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!