Computer Science, asked by prantkeshari677, 4 months ago

Consider the following dictionary: stock={"Garments":350,"Toys":2000,"Snacks":450,"Cosmetic":1200} Write a Python statement by calling functions related to dictionary for each question given below: 1)To display total elements in a dictionary 2)To display list of values 3)To display list of keys 4)To display the value of given key and if key not found in the dictionary then it should display message out of stock 5)To delete the key Snacks and also display its value before deletion 6)To delete all the elements of dictionary OR Write a program to sort the values of given list using Bubble Sort algorithm? score=[87,45,67,23,90,12] ​

Answers

Answered by Equestriadash
9

Given dictionary:

stock = {"Garments":350, "Toys":2000, "Snacks":450, "Cosmetic":1200}

1)To display the total number of elements in the dictionary.

>>> len(stock)

2) To display the list of values.

>>> stock.values()

3) To display the list of keys.

>>> stock.keys()

4) To display the value of a given key and if the key is not found in the dictionary, it should display the message: 'Out of stock'.

>>> n = input("Enter the stock name: ")

>>> stock.get(n, "Out of stock")

5. To delete the key 'Snacks' and also display its value before deletion.

>>> stock.pop('Snacks')

6. To delete all the elements of the dictionary.

>>> stock.clear()

  • len() is a function that calculates the length.
  • values() is a method that retrieves the values from a dictionary in the form of a list.
  • keys() is a method that retrieves the keys of a dictionary in the form of a list.
  • get() is a method the retrieves the value of the specified key/prints an optional message if the key isn't in the dictionary.
  • pop() is a method that removes the specified key from the dictionary and returns its value.
  • clear() is a method that clears the dictionary.
Similar questions