0 out of 464 challenges solved
Write a Python function `expensive_items(items, n)` that takes a list of dictionaries `items` and an integer `n` as input. Each dictionary in the list represents an item with at least two keys: `name` (a string) and `price` (a float). The function should return a list of the `n` most expensive items, sorted in descending order of their prices.
If there are fewer than `n` items in the list, return all items sorted by price. If two items have the same price, their order in the result can be arbitrary.
#### Example Usage
```python [main.nopy]
items = [
{'name': 'Item-1', 'price': 101.1},
{'name': 'Item-2', 'price': 555.22},
{'name': 'Item-3', 'price': 45.09}
]
print(expensive_items(items, 2))
# Output: [{'name': 'Item-2', 'price': 555.22}, {'name': 'Item-1', 'price': 101.1}]
print(expensive_items(items, 1))
# Output: [{'name': 'Item-2', 'price': 555.22}]
```
#### Constraints
- The `items` list will contain dictionaries with at least the keys `name` and `price`.
- The `price` values will be non-negative floats.
- The function should handle cases where `n` is greater than the number of items in the list.import heapq
def expensive_items(items, n):
"""
Find the n most expensive items from the given list.
Args:
items (list): A list of dictionaries, each containing 'name' and 'price'.
n (int): The number of top expensive items to return.
Returns:
list: A list of the n most expensive items sorted by price in descending order.
"""
# Placeholder for the solution
pass