KnowledgeBoat Logo
OPEN IN APP

Chapter 6

Dictionary

Class 11 - Informatics Practices Preeti Arora



Fill in the Blanks

Question 1

Like lists, Dictionaries are mutable which means they can be changed.

Question 2

A Python dictionary is a mapping of unique keys to values. It is a collection of key-value pairs.

Question 3

The association of a key and a value is called a Key-Value pair.

Question 4

To create a dictionary, key-value pairs are separated by comma.

Question 5

In key-value pair, each key is separated from its value by a colon(:).

Question 6

keys() function returns the keys of the dictionary.

Question 7

Keys of a dictionary must be unique.

Question 8

To delete an element, you can either use del statement or use pop() method.

Question 9

The len() function returns total number of key-value pairs in a dictionary.

Question 10

Accessing a value specified by a key, which is not in a dictionary using get() function, returns None.

State True or False

Question 1

An element in a dictionary is a combination of key-value pairs.

Answer

True

Reason — In a dictionary, an element is a combination of key-value pairs.

Question 2

Internally, dictionaries are indexed on the basis of values.

Answer

False

Reason — The elements in a dictionary are indexed by keys and not values.

Question 3

We can repeat a key in dictionary.

Answer

False

Reason — Keys are unique and immutable in a dictionary.

Question 4

In dictionary, two unique keys can have the same values.

Answer

True

Reason — In a dictionary, while each key must be unique, multiple keys can have the same value.

Question 5

clear() is used to delete a dictionary.

Answer

False

Reason — The clear() method is used to remove all items from the particular dictionary and returns an empty dictionary.

Question 6

The key of a dictionary is a mutable data type.

Answer

False

Reason — The key of a dictionary is an immutable data type.

Question 7

List can be used as keys in a dictionary.

Answer

False

Reason — Lists cannot be used as keys in a dictionary because they are mutable. Dictionary keys must be immutable.

Question 8

Updating an element in a dictionary at runtime is possible.

Answer

True

Reason — Updating an element in a dictionary at runtime is possible because dictionaries are mutable data structures.

Question 9

We can create immutable dictionaries in Python.

Answer

False

Reason — We cannot create immutable dictionaries in Python because dictionaries are mutable.

Multiple Choice Questions

Question 1

Which of the statement(s) is/are correct?

  1. In Python dictionary, the key-value pair is called an item.
  2. Python dictionary is a mapping of unique keys to values.
  3. Dictionary is mutable.
  4. All of these.

Answer

All of these.

Reason — A dictionary is mutable and consists of elements in the form of key-value pairs, where each pair is termed an item. It maps unique keys to values.

Question 2

To create an empty dictionary, we use the statement as:

  1. d1 = {}
  2. d1 = []
  3. d1 = ()
  4. d1 == {}

Answer

d1 = {}

Reason — The statement to create an empty dictionary in Python is d1 = {}.

Question 3

In a dictionary, the elements are accessed through:

  1. key
  2. value
  3. label
  4. None of these

Answer

key

Reason — In a dictionary, elements are accessed using keys, which uniquely identifies each element's associated value.

Question 4

Keys of a dictionary must be:

  1. Similar
  2. Unique
  3. Both (i) and (ii)
  4. All of these

Answer

Unique

Reason — Keys of a dictionary must be unique and immutable.

Question 5

To create a new dictionary with no items:

  1. Dict
  2. dict()
  3. d1={}
  4. Both 2 and 3

Answer

Both 2 and 3

Reason — The function dict() and d1 = {} are both used to create a new dictionary with no items.

Question 6

Which function is used to return a value for the given key?

  1. len()
  2. get()
  3. keys()
  4. None of these

Answer

get()

Reason — The get() method returns a value for the given key. If key is not available, then returns the default value None.

Question 7

Which function is used to remove all items from a particular dictionary?

  1. clear()
  2. pop()
  3. delete()
  4. rem()

Answer

clear()

Reason — The clear() function is used to remove all items from the particular dictionary and returns an empty dictionary.

Question 8

What will be the output of the following Python code snippet?

d1 = { "amit" :40, "jatin" :45}
d2 = { "amit" :466, "jatin" :45}
d1 > d2
  1. True
  2. False
  3. Error
  4. None

Answer

Error

Reason — In Python, we cannot directly compare dictionaries using the > or < operators. Attempting to do so will result in a Error because dictionaries are unordered collections.

Question 9

Which of the following functions will return key-value pairs of the dictionary in the form of list of tuples?

  1. key()
  2. values()
  3. items()
  4. get()

Answer

items()

Reason — The items() function will return key-value pairs of the dictionary in the form of list of tuples.

Question 10

Select the correct option to get the values of marks key:

Student={ "name" : "Emma", "class" :11, "sec": "a", "marks" :76}
  1. Student.get(3)
  2. Student.get("marks")
  3. Student["marks"]
  4. Both 2 and 3

Answer

Both 2 and 3

ReasonStudent.get("marks") and Student["marks"] both access the value associated with the key "marks" in the Student dictionary. While Student.get(3) would return "None" because there is no key 3 in the dictionary.

Question 11

Consider the given code:

D1={1: 'India', 2: 'Russia', 3: 'World'}
D2={'School' : 'EOIS' , 'Place ' : 'Moscow'}
print(D1.update (D2) )

What will be the output of the above code:

  1. None
  2. {1: 'India' , 2: 'Russia' , 3: 'World' , 'School' : 'EOIS' , 'Place' : 'Moscow'}
  3. Error
  4. None of these

Answer

None

Reason — The output is "None" when using print(D1.update(D2)) because the update() method for dictionaries modifies the dictionary in place. It does not return the updated dictionary itself; instead, it returns "None".

Assertions and Reasons

Question 1

Assertion (A): Dictionary is a collection of key-value pairs.

Reasoning (R): Each key in a dictionary maps to a corresponding value. Keys are unique and act as the index.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
A dictionary is a collection of key-value pairs, where each key is unique and maps to a corresponding value. The keys act as the index, allowing to access and manipulate the values associated with them.

Question 2

Assertion (A): Dictionaries are enclosed within curly braces { }.

Reasoning (R): The key-value pairs are separated by commas (,).

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true but R is not the correct explanation of A.

Explanation
Dictionaries in Python are enclosed within curly braces {}, where each key is separated from its corresponding value by a colon (:), and different key-value pairs are separated by commas.

Question 3

Assertion (A): The popitem() method can be used to delete elements from a dictionary.

Reasoning (R): The popitem() method deletes the last inserted key-value pair and returns the value of deleted element.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The popitem() method in Python is used to delete elements from a dictionary. It returns and removes the last inserted key-value pair from the dictionary.

Question 4

Assertion (A): Keys of the dictionaries must be unique.

Reasoning (R): The keys of a dictionary can be accessed using values.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
The keys of dictionaries in Python must be unique and immutable. Values in a dictionary can be accessed using their corresponding keys.

Question 5

Assertion (A): clear() method removes all elements from the dictionary.

Reasoning (R): len() function cannot be used to find the length of a dictionary.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
The clear() method removes all items from the particular dictionary and returns an empty dictionary. The len() method returns the length of key-value pairs in the given dictionary.

Question 6

Assertion (A): Items in dictionaries are unordered.

Reasoning (R): You may not get back the data in the same order in which you had entered the data initially in the dictionary.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
In Python, items in dictionaries are unordered. Dictionaries do not maintain the order of elements as they are inserted. When retrieving data from a dictionary, the order of elements returned may not match the order in which they were inserted.

Question 7

Assertion (A): Consider the code given below:

d={1: 'Amit', 2: 'Sumit', 5:'Kavita'}
d.pop(1) 
print(d) 

The output will be:

Amit #item is returned after deletion
{2: 'Sumit', 5: 'Kavita'}

Reasoning (R): pop() method not only deletes the item from the dictionary but also returns the deleted value.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
In the given code, when d.pop(1) is called, it removes the key 1 and returns the corresponding value 'Amit'. The subsequent print(d) statement displays the updated dictionary without the key-value pair (1, 'Amit'). The pop() method in Python dictionaries not only deletes the specified key-value pair from the dictionary but also returns the value associated with the deleted key.

Solutions to Unsolved Questions

Question 1

What is a key-value pair in dictionary?

Answer

A key-value pair in a dictionary is an association of a key and its corresponding value.

Question 2

What are the differences between strings and dictionary?

Answer

StringDictionary
A string is a sequence of characters enclosed in quotes.A dictionary is a collection of key-value pairs enclosed in curly braces {}.
It is immutable.It is mutable.
Strings are ordered collection of objects.Dictionaries are unordered collections of objects.
For example, "hello", '123' etc.For example, {1: 'a', 2 : 'b'} etc

Question 3(a)

Find errors and rewrite the same after correcting the following code:

d1 = {1:10, 2.5:20, 3:30, 4:40, 5:50, 6:60, 7:70}

Answer

The given code is syntactically correct and doesn't contain any errors.

Question 3(b)

Find errors and rewrite the same after correcting the following code:

d1(9) = 90 

Answer

In Python, we assign the key-value pair using square brackets [], not parentheses ().

The corrected code is:

d1[9] = 90

Question 3(c)

Find errors and rewrite the same after correcting the following code:

del d1(2)  

Answer

In Python, to delete an element from a dictionary, we should use square brackets [], not parentheses ().

The corrected code is:

del d1[2]

Question 3(d)

Find errors and rewrite the same after correcting the following code:

pop d1[4]

Answer

Th syntax of pop() method is dictname.pop(key).

The corrected code is:

d1.pop(4)

Question 3(e)

Find errors and rewrite the same after correcting the following code:

d1.item()

Answer

The correct method to retrieve all key-value pairs from a dictionary is items(), not item().

The corrected code is:

d1.items()

Question 3(f)

Find errors and rewrite the same after correcting the following code:

d1.key()

Answer

The correct method to retrieve all keys from a dictionary is keys(), not key().

The corrected code is:

d1.keys()

Question 3(g)

Find errors and rewrite the same after correcting the following code:

d1.value()

Answer

The correct method to retrieve all values from a dictionary is values(), not value().

The corrected code is:

d1.values()

Question 3(h)

Find errors and rewrite the same after correcting the following code:

d1.gets(4, 80) 

Answer

The correct method to retrieve a value for a given key is get(), not gets().

The corrected code is:

d1.get(4, 80)

Question 3(i)

Find errors and rewrite the same after correcting the following code:

d1.len()

Answer

The syntax of len() function is len(dict).

The corrected code is:

len(d1)

Question 3(j)

Find errors and rewrite the same after correcting the following code:

d1.clears()  

Answer

The correct method to clear all elements from a dictionary is clear(), not clears().

The corrected code is:

d1.clear()

Question 4(a)

Suppose

>>> d1 = { 1 : 'one' , 2: 'two' , 3: 'three' , 4: 'four'}
>>> d2 = { 5 :'five', 6:'six' }

Write the output of the following code:

>>> d1.items() 
>>> d1.keys() 
>>> d1.values() 
>>> d1.update(d2)
>>> len(d1)

Answer

Output
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
dict_keys([1, 2, 3, 4])
dict_values(['one', 'two', 'three', 'four'])
6
Explanation
  1. d1.items() — Returns a list of tuples containing the key-value pairs in d1.
  2. d1.keys() — Returns a list of all the keys in d1.
  3. d1.values() — Returns a list of all the values in d1.
  4. d1.update(d2) — Updates d1 with key-value pairs from d2. After this operation, d1 contains {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six'}.
  5. len(d1) — Returns the number of key-value pairs in d1, which is 6 after updating.

Question 4(b)

Suppose

>>> d1 = { 1 : 'one' , 2: 'two' , 3: 'three' , 4: 'four'}
>>> d2 = { 5 :'five', 6:'six' }

Write the output of the following code:

>>> del d1[3] 
>>> print(d1) 
>>> d1.pop(4) 
>>> print(d1) 
>>> d1 [8] =' eight'
>>> print(d1) 
>>> d1.clear() 
>>> print(d1)

Answer

Output
{1: 'one', 2: 'two', 4: 'four'}
'four'
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 8: ' eight'}
{}
Explanation
  1. del d1[3]: Removes the key 3 and its corresponding value 'three' from d1. After deletion, d1 contains {1: 'one', 2: 'two', 4: 'four'}.
  2. d1.pop(4): Removes the key 4 and its corresponding value 'four' from d1. After popping, d1 is {1: 'one', 2: 'two'}.
  3. d1[8] = 'eight': Adds a new key-value pair 8: 'eight' to d1. Now d1 becomes {1: 'one', 2: 'two', 8: 'eight'}.
  4. d1.clear(): Clears all key-value pairs from d1, resulting in an empty dictionary {}.

Question 5

Write a Python program to find the highest 2 values in a dictionary.

Solution
d = {'a': 10, 'b': 30, 'c': 20, 'd': 50, 'e': 40}
s = sorted(d.values())
print("Dictionary:", d)
print("Highest 2 values are:", s[-1], s[-2])
Output
Dictionary: {'a': 10, 'b': 30, 'c': 20, 'd': 50, 'e': 40}
Highest 2 values are: 50 40

Question 6

Write a Python program to input 'n' classes and names of their class teachers to store it in a dictionary and display the same. Also, accept a particular class from the user and display the name of the class teacher of that class.

Solution
n = int(input("Enter number of classes: "))
data = {}
for i in range(n):
    class_name = input("Enter class name: ")
    teacher_name = input("Enter teacher name: ")
    data[class_name] = teacher_name
print("Class data:", data)
find = input("Enter a class name to find its teacher: ")
if find in data:
    print("Teacher for class", find, "is", data[find])
else:
    print("Class not found in the data.")
Output
Enter number of classes: 4
Enter class name: green
Enter teacher name: Aniket
Enter class name: yellow
Enter teacher name: Pratibha
Enter class name: red
Enter teacher name: Mayuri
Enter class name: blue
Enter teacher name: Prithvi
Class data: {'green': 'Aniket', 'yellow': 'Pratibha', 'red': 'Mayuri', 'blue': 'Prithvi'}
Enter a class name to find its teacher: red
Teacher for class red is Mayuri

Question 7

Write a program to store students' names and their percentage in a dictionary, and delete a particular student name from the dictionary. Also display dictionary after deletion.

Solution
n = int(input("Enter number of students: "))
data = {}
for i in range(n):
    stu_name = input("Enter student name: ")
    percentage = input("Enter percentage: ")
    data[stu_name] = percentage
print("Student data:", data)
find = input("Enter a student name to delete: ")
if find in data:
    del data[find]
    print("Updated student data:", data)
else:
    print("Student not found in the data.")
Output
Enter number of students: 4
Enter student name: Megha
Enter percentage: 98
Enter student name: Amit
Enter percentage: 88
Enter student name: Nitin
Enter percentage: 92
Enter student name: Amulya
Enter percentage: 79
Student data: {'Megha': '98', 'Amit': '88', 'Nitin': '92', 'Amulya': '79'}
Enter a student name to delete: Nitin
Updated student data: {'Megha': '98', 'Amit': '88', 'Amulya': '79'}

Question 8

Write a Python program to input names of 'n' customers and their details like items bought, cost and phone number, store it in a dictionary and display all the details in a tabular form.

Solution
n = int(input("Enter the number of customers: "))
customer_data = {}

for i in range(n):
    name = input("Enter customer name: ")
    items_bought = input("Enter items bought: ")
    cost = float(input("Enter cost: "))
    phone_number = int(input("Enter phone number: "))

    customer_data[name] = {
        'Items Bought': items_bought,
        'Cost': cost,
        'Phone Number': phone_number
    }

print("Customer Details:")
print("Name\t\tItems Bought\t\tCost\t\tPhone Number")
for name, details in customer_data.items():
    print(name, "\t\t", details['Items Bought'], "\t\t", details['Cost'], "\t\t", details['Phone Number'])
Output
Enter the number of customers: 4
Enter customer name: Sakshi
Enter items bought: Chocolate, Icecream
Enter cost: 200
Enter phone number: 9876354678
Enter customer name: Shashank
Enter items bought: Biscuits, Maggie, Soup
Enter cost: 450
Enter phone number: 8976346378
Enter customer name: Saanvi
Enter items bought: Veggies, Coffee
Enter cost: 300
Enter phone number: 8794653923
Enter customer name: Shivank
Enter items bought: Door mat, Bottles, Boxes
Enter cost: 600
Enter phone number: 6737486827
Customer Details:
Name            Items Bought            Cost            Phone Number
Sakshi           Chocolate, Icecream             200.0           9876354678
Shashank                 Biscuits, Maggie, Soup                  450.0           8976346378
Saanvi           Veggies, Coffee                 300.0           8794653923
Shivank                  Door mat, Bottles, Boxes                600.0           6737486827

Question 9

What type of objects can be used as keys in dictionaries?

Answer

Keys of a dictionary must be of immutable types such as

  1. a Python string
  2. a number
  3. a tuple (containing only immutable entries)

Question 10

How will you check for a value inside a dictionary using in operator?

Answer

We cannot directly check for a value inside a dictionary using in operator since in operator searches for a key in a dictionary. We can use values() function along with in operator to check for a value in dictionary as shown below:

>>> d = {1: 'a' , 2:'b'}
>>> 'b' in d.values()

Output

True

Question 11

How is clear() function different from del statement?

Answer

The clear() function removes all the key:value pairs from the dictionary and makes it empty dictionary while del <dict> statement removes the complete dictionary as an object. After del statement with a dictionary name, that dictionary object no more exists, not even empty dictionary.

For example:

d = {1: 'a' , 2 : 'b'} 
d.clear()
print(d)
del d
print(d)

Output

{}
NameError: name 'd' is not defined.

Question 12

The following code is giving some error. Find out the error and write the corrected code.

d1 = { "a" : 1, 1 : "a", [1, "a"] : "two"}

Answer

This type of error occurs when a mutable type is used as a key in dictionary. In d1, [1, "a"] is used as a key which is a mutable type of list. It will generate the below error:

TypeError: unhashable type: 'list'

This error can be fixed by using a tuple as a key instead of list as shown below:

d1 = {"a" : 1, 1 : "a", (1, "a") : "two"}

Question 13

What will be the output of the following code?

d1 = {5: [6,7,8], "a": (1,2,3)} 
print (d1.keys () )
print (d1.values () )

Answer

Output
dict_keys([5, 'a'])  
dict_values([[6, 7, 8], (1, 2, 3)])  
Explanation

keys() function returns all the keys defined in the dictionary in the form of a list. values() function returns all the values defined in the dictionary in the form of a list.

Question 14(a)

Write the output of the following code:

d = { (1,2):1, (2,3):21 }
print (d[1,2] )

Answer

Output
1
Explanation

In the given code, d is a dictionary that has tuples (1,2) and (2,3) as keys mapped to their respective values 1 and 21. When we access d[1, 2], Python interprets (1,2) as a tuple and looks for this tuple as a key in dictionary d. Therefore, it retrieves the value associated with the key (1,2), which is 1.

Question 14(b)

Write the output of the following code:

d = {'a':1, 'b':2, 'c':3}
print (d['a'])

Answer

Output
1
Explanation

In the above code, d is a dictionary initialized with keys 'a', 'b', and 'c', each mapped to their respective values 1, 2, and 3. When print(d['a']) is executed, Python retrieves the value associated with the key 'a' from dictionary d. Therefore, the output of print(d['a']) will be 1.

Question 15

Write a program to input your friends' names and their phone numbers and store them in a dictionary as the key-value pair. Perform the following operations on the dictionary:

(a) Display the Name and Phone numbers of all your friends.

(b) Add a new key-value pair in this dictionary and display the modified dictionary.

(c) Delete a particular friend from the dictionary.

(d) Modify the phone number of an existing friend.

(e) Check if a friend is present in the dictionary or not.

(f) Display the dictionary in sorted order of names.

Solution
phonebook = {}

num_friends = int(input("Enter how many friends: "))

for i in range(num_friends):
    name = input("Enter name of friend: ")
    phone = input("Enter phone number: ")
    phonebook[name] = phone

# (a) Display the Name and Phone numbers of all your friends.
print("Friends and their phone numbers:")
for name, number in phonebook.items():
    print(name + ": " + number)

# (b) Add a new key-value pair in this dictionary and display the modified dictionary.
new_name = input("\nEnter name of new friend: ")
new_number = input("Enter phone number of new friend: ")
phonebook[new_name] = new_number
print(phonebook)

# (c) Delete a particular friend from the dictionary.
del_name = input("\nEnter name of friend to delete: ")
if del_name in phonebook:
    del phonebook[del_name]
    print(del_name + " has been deleted.")
else:
    print(del_name + " not found.")
print(phonebook)

# (d) Modify the phone number of an existing friend.
mod_name = input("\nEnter name of friend to modify number: ")
if mod_name in phonebook:
    mod_number = input("Enter new phone number: ")
    phonebook[mod_name] = mod_number
    print(mod_name + "'s phone number has been modified.")
else:
    print(mod_name + " not found.")
print(phonebook)

# (e) Check if a friend is present in the dictionary or not.
check_name = input("\nEnter name of friend to check: ")
if check_name in phonebook:
    print(check_name + " is present in the dictionary.")
else:
    print(check_name + " is not present in the dictionary.")

# (f) Display the dictionary in sorted order of names.
sorted_keys = sorted(phonebook)
print("\nDictionary in sorted order of names:")
print("{", end = " ")
for key in sorted_keys:
    print(key, ":", phonebook[key], end = " ")
print("}")
Output
Enter how many friends: 3
Enter name of friend: Mayuri
Enter phone number: 7689874888
Enter name of friend: Ankit
Enter phone number: 6748584757
Enter name of friend: Ashish
Enter phone number: 9088378388
Friends and their phone numbers:
Mayuri: 7689874888
Ankit: 6748584757
Ashish: 9088378388

Enter name of new friend: Sahini
Enter phone number of new friend: 8978909877
{'Mayuri': '7689874888', 'Ankit': '6748584757', 'Ashish': '9088378388', 'Sahini': '8978909877'}

Enter name of friend to delete: Mayuri
Mayuri has been deleted.
{'Ankit': '6748584757', 'Ashish': '9088378388', 'Sahini': '8978909877'}

Enter name of friend to modify number: Ankit
Enter new phone number: 8989587587
Ankit's phone number has been modified.
{'Ankit': '8989587587', 'Ashish': '9088378388', 'Sahini': '8978909877'}

Enter name of friend to check: Ashish
Ashish is present in the dictionary.

Dictionary in sorted order of names:
{ Ankit : 8989587587 Ashish : 9088378388 Sahini : 8978909877 }

Question 16

Consider the following dictionary Prod_Price.

Prod_Price = {'LCD' : 25000,
                'Laptop' : 35000, 
                'Home Theatre' : 80000,
                'Microwave Oven' : 18000,
                'Electric Iron' : 2800,
                'Speaker' : 55000}

Find the output of the following statements:

(a) print(Prod_Price.get('Laptop'))

(b) print(Prod_Price.keys())

(c) print(Prod_Price.values())

(d) print(Prod_Price.items())

(e) print(len(Prod_Price))

(f) print('Speaker' in Prod_Price)

(g) print(Prod_Price.get('LCD'))

(h) del Prod_Price['Home Theatre']
     print (Prod_Price)

Answer

(a) 35000

(b) dict_keys(['LCD', 'Laptop', 'Home Theatre', 'Microwave Oven', 'Electric Iron', 'Speaker'])

(c) dict_values([25000, 35000, 80000, 18000, 2800, 55000])

(d) dict_items([('LCD', 25000), ('Laptop', 35000), ('Home Theatre', 80000), ('Microwave Oven', 18000), ('Electric Iron', 2800), ('Speaker', 55000)])

(e) 6

(f) True

(g) 25000

(h) {'LCD': 25000, 'Laptop': 35000, 'Microwave Oven': 18000, 'Electric Iron': 2800, 'Speaker': 55000}

Explanation

(a) The get() method retrieves the value associated with the key 'Laptop'. The value (35000) is returned.

(b) The keys() method returns all the keys of the dictionary as a list.

(c) The values() method returns a list of values from key-value pairs in a dictionary.

(d) The items() method returns all the key-value pairs of the dictionary as a list of tuples.

(e) The len() function returns the number of key-value pairs (items) in the dictionary. In this case, there are 6 items in the dictionary.

(f) The in keyword is used to check if the key 'Speaker' is present in the dictionary. If the key exists, it returns True; otherwise, it returns False.

(g) The get() method retrieves the value associated with the key 'LCD'. The value (25000) is returned.

(h) The del statement removes the key 'Home Theatre' and its associated value from the dictionary. After deletion, the dictionary is printed, showing the remaining items.

Question 17

Write a program that prompts the user for product names and prices, and store these key-value pairs in a dictionary where names are the keys and prices are the values. Also, write a code to search for a product in a dictionary and display its price. If the product is not there in the dictionary, then display the relevant message.

Solution
prodDict = {}

n = int(input("Enter the number of products: "))

for i in range(n):
    name = input("Enter the name of product: ")
    price = float(input("Enter the price: "))
    prodDict[name] = price

print(prodDict)

pName = input("\nEnter product name to search: ")

if pName in prodDict:
    print("The price of", pName, "is: ", prodDict[pName])
else:
    print("Product", pName, " not found.")
Output
Enter the number of products: 4
Enter the name of product: Television
Enter the price: 20000
Enter the name of product: Computer
Enter the price: 30000
Enter the name of product: Mobile
Enter the price: 50000
Enter the name of product: Air-Cooler
Enter the price: 35000
{'Television': 20000.0, 'Computer': 30000.0, 'Mobile': 50000.0, 'Air-Cooler': 35000.0}

Enter product name to search: Mobile
The price of Mobile is:  50000.0

Question 18

Write a Python program that accepts a value and checks whether the inputted value is part of the given dictionary or not. If it is present, check for the frequency of its occurrence and print the corresponding key, otherwise print an error message.

Solution
d = {
    'A': 'apple',
    'B': 'banana',
    'C': 'apple',
    'D': 'orange',
    'E': 'strawberry'
}

v = input("Enter a value to check: ")
k = []

for key, value in d.items():
    if value == v:
        k.append(key)

if len(k) > 0:
    print("The value", v, "is present in the dictionary.")
    print("It occurs", len(k), "time(s) and is associated with the following key(s):", k)
else:
    print("The value", v, "is not present in the dictionary.")
Output
Enter a value to check: apple
The value apple is present in the dictionary.
It occurs 2 time(s) and is associated with the following key(s): ['A', 'C']
PrevNext