95,008 views
13 votes
13 votes
Write a program get_price.py with a function get_price() that takes a dictionary of fruits as an argument and returns the name of the most expensive fruit. Each item of the dictionary includes: A key: the name of the fruit A value: the price of the fruit.

User Joe Bourne
by
2.8k points

1 Answer

11 votes
11 votes

Answer:

The program is as follows:

def get_price(fruits):

AllPrice = fruits.values()

value_iterator = iter(AllPrice)

mostExpensive = next(value_iterator)

for item in fruits:

if fruits[item]>=mostExpensive:

mostExpensive = fruits[item]

fruitName = item

print(fruitName)

fruits = {}

n = int(input("Number of Fruits: "))

for i in range(n):

name = input("Fruit name: ")

price = int(input("Fruit price: "))

fruits[name] = price

get_price(fruits)

Step-by-step explanation:

This defines the get_price function

def get_price(fruits):

This gets all price in the dictionary fruit

AllPrice = fruits.values()

This passes the values to a value iterator

value_iterator = iter(AllPrice)

This initializes mostExpensive to the first price in the dictionary

mostExpensive = next(value_iterator)

This iterates through the elements of the dictionary

for item in fruits:

If current element is greater than or equals most expensive

if fruits[item]>=mostExpensive:

Set most expensive to the current element

mostExpensive = fruits[item]

Get the corresponding fruit name

fruitName = item

Print fruit name

print(fruitName)

The main begins here

This initializes the fruit dictionary

fruits = {}

This gets input for the number of fruits

n = int(input("Number of Fruits: "))

This is repeated for every inputs

for i in range(n):

Get fruit name

name = input("Fruit name: ")

Get fruit price

price = int(input("Fruit price: "))

Append name and price to dictionary

fruits[name] = price

Call the get_price function

get_price(fruits)

User Matheus
by
3.1k points