Loading...
Please wait while we prepare your content
Please wait while we prepare your content
Solutions for Informatics Practices, Class 11, CBSE
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.
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.
Assertion (A): Dictionaries are enclosed within curly braces { }.
Reasoning (R): The key-value pairs are separated by commas (,).
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.
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.
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.
Assertion (A): Keys of the dictionaries must be unique.
Reasoning (R): The keys of a dictionary can be accessed using values.
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.
Assertion (A): clear() method removes all elements from the dictionary.
Reasoning (R): len() function cannot be used to find the length of a dictionary.
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.
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.
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.
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.
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.
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.
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.
Both 2 and 3
Reason — Student.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.
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:
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".
String | Dictionary |
---|---|
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 |
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
dict_keys([1, 2, 3, 4])
dict_values(['one', 'two', 'three', 'four'])
6
d1.items()
— Returns a list of tuples containing the key-value pairs in d1
.d1.keys()
— Returns a list of all the keys in d1
.d1.values()
— Returns a list of all the values in d1
.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'}.len(d1)
— Returns the number of key-value pairs in d1
, which is 6 after updating.{1: 'one', 2: 'two', 4: 'four'}
'four'
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 8: ' eight'}
{}
del d1[3]
: Removes the key 3 and its corresponding value 'three' from d1
. After deletion, d1
contains {1: 'one', 2: 'two', 4: 'four'}.d1.pop(4)
: Removes the key 4 and its corresponding value 'four' from d1
. After popping, d1
is {1: 'one', 2: 'two'}.d1[8] = 'eight'
: Adds a new key-value pair 8: 'eight' to d1
. Now d1
becomes {1: 'one', 2: 'two', 8: 'eight'}.d1.clear()
: Clears all key-value pairs from d1
, resulting in an empty dictionary {}
.Write a Python program to find the highest 2 values in a dictionary.
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])
Dictionary: {'a': 10, 'b': 30, 'c': 20, 'd': 50, 'e': 40}
Highest 2 values are: 50 40
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.
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.")
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
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.
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.")
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'}
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.
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'])
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
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
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.
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"}
1
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.
1
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.
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.
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("}")
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 }
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)
(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.
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.
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.")
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
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.
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.")
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']