84 views
Напишите функцию get(obj, path), которая принимает объект obj и строку path, представляющую путь к вложенному значению в этом объекте. Путь состоит из ключей, разделённых точкой ( . ). - Если путь существует — функция должна вернуть значение, найденное по этому пути. - Если путь не существует (на любом уровне вложенности отсутствует нужный ключ, либо промежуточное значение не является объектом) — функция должна вернуть undefined. Входные данные: - obj — произвольный объект с вложенной структурой (ключи — строки, значения — любые типы, включая вложенные объекты) - path — строка вида "a.b.c", представляющая путь к значению Выходные данные: Значение по указанному пути, либо undefined, если путь не найден. Ограничения: - Глубина вложенности от 1 до 10 - Ключи пути состоят из букв, цифр и _ - obj может быть пустым объектом Пример: ```python # Доступно без импорта: json, sys, io def get(obj, path): # TODO: напишите решение здесь return None ```
Asked at
AI answer
def get(obj, path):
current = obj
for key in path.split("."):
if not isinstance(current, dict) or key not in current:
return None
current = current[key]
return current
In Python, None is used as the equivalent of undefined in the problem statement. Checking key not in current makes it possible to correctly return an existing value, even if that value is None.
Also asked at getmatch agency
- Why did you leave your previous job?
- What types of data are there in Python?
- Tell us about your work experience.
- A user uploads a video and selects the desired processing, which he wants to get. The service accepts the video, applies the necessary processing, and outputs the final result. By processing, we can understand, for example, the following: make the video black and white, flip it, speed it up N times, etc. It is important that the user can monitor the progress of the processing. Load: 10,000 videos per minute
- What frameworks have you worked with?
Similar questions
- How to safely get a value by key from a nested dictionary if you're not sure whether the key exists?
- How can you get or modify the value of an object's attribute in Python?
- How can you parse JSON data using Python?
- What does the dict.get() method return if the key is missing?
- Write a function that converts a list of records into a dictionary grouped by city, without explicitly checking whether a key exists.