Like lists, Dictionaries are mutable which means they can be changed.
A Python dictionary is a mapping of unique keys to values. It is a collection of key-value pairs.
The association of a key and a value is called a Key-Value pair.
To create a dictionary, key-value pairs are separated by comma.
In key-value pair, each key is separated from its value by a colon(:).
keys() function returns the keys of the dictionary.
Keys of a dictionary must be unique.
To delete an element, you can either use del statement or use pop() method.
The len() function returns total number of key-value pairs in a dictionary.
Accessing a value specified by a key, which is not in a dictionary using get() function, returns None.
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.
Internally, dictionaries are indexed on the basis of values.
Answer
False
Reason — The elements in a dictionary are indexed by keys and not values.
We can repeat a key in dictionary.
Answer
False
Reason — Keys are unique and immutable in a dictionary.
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.
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.
The key of a dictionary is a mutable data type.
Answer
False
Reason — The key of a dictionary is an immutable data type.
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.
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.
We can create immutable dictionaries in Python.
Answer
False
Reason — We cannot create immutable dictionaries in Python because dictionaries are mutable.
Which of the statement(s) is/are correct?
- In Python dictionary, the key-value pair is called an item.
- Python dictionary is a mapping of unique keys to values.
- Dictionary is mutable.
- 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.
To create an empty dictionary, we use the statement as:
- d1 = {}
- d1 = []
- d1 = ()
- d1 == {}
Answer
d1 = {}
Reason — The statement to create an empty dictionary in Python is d1 = {}
.
In a dictionary, the elements are accessed through:
- key
- value
- label
- None of these
Answer
key
Reason — In a dictionary, elements are accessed using keys, which uniquely identifies each element's associated value.
Keys of a dictionary must be:
- Similar
- Unique
- Both (i) and (ii)
- All of these
Answer
Unique
Reason — Keys of a dictionary must be unique and immutable.
To create a new dictionary with no items:
- Dict
- dict()
- d1={}
- 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.
Which function is used to return a value for the given key?
- len()
- get()
- keys()
- 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.
Which function is used to remove all items from a particular dictionary?
- clear()
- pop()
- delete()
- rem()
Answer
clear()
Reason — The clear()
function is used to remove all items from the particular dictionary and returns an empty dictionary.
What will be the output of the following Python code snippet?
d1 = { "amit" :40, "jatin" :45}
d2 = { "amit" :466, "jatin" :45}
d1 > d2
- True
- False
- Error
- 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.
Which of the following functions will return key-value pairs of the dictionary in the form of list of tuples?
- key()
- values()
- items()
- get()
Answer
items()
Reason — The items()
function will return key-value pairs of the dictionary in the form of list of tuples.
Select the correct option to get the values of marks key:
Student={ "name" : "Emma", "class" :11, "sec": "a", "marks" :76}
- Student.get(3)
- Student.get("marks")
- Student["marks"]
- Both 2 and 3
Answer
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
- {1: 'India' , 2: 'Russia' , 3: 'World' , 'School' : 'EOIS' , 'Place' : 'Moscow'}
- Error
- 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".
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.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
Assertion (A): Dictionaries are enclosed within curly braces { }.
Reasoning (R): The key-value pairs are separated by commas (,).
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
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.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
Assertion (A): Keys of the dictionaries must be unique.
Reasoning (R): The keys of a dictionary can be accessed using values.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
Assertion (A): clear() method removes all elements from the dictionary.
Reasoning (R): len() function cannot be used to find the length of a dictionary.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
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.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
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.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
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.
What are the differences between strings and dictionary?
Answer
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 |
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.
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
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]
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)
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()
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()
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()
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)
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)
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()
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
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 ind1
.d1.keys()
— Returns a list of all the keys ind1
.d1.values()
— Returns a list of all the values ind1
.d1.update(d2)
— Updatesd1
with key-value pairs fromd2
. 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 ind1
, which is 6 after updating.
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
{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' fromd1
. After deletion,d1
contains {1: 'one', 2: 'two', 4: 'four'}.d1.pop(4)
: Removes the key 4 and its corresponding value 'four' fromd1
. After popping,d1
is {1: 'one', 2: 'two'}.d1[8] = 'eight'
: Adds a new key-value pair 8: 'eight' tod1
. Nowd1
becomes {1: 'one', 2: 'two', 8: 'eight'}.d1.clear()
: Clears all key-value pairs fromd1
, 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
What type of objects can be used as keys in dictionaries?
Answer
Keys of a dictionary must be of immutable types such as
- a Python string
- a number
- a tuple (containing only immutable entries)
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
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.
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"}
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
dict_keys([5, 'a'])
dict_values([[6, 7, 8], (1, 2, 3)])
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.
Write the output of the following code:
d = { (1,2):1, (2,3):21 }
print (d[1,2] )
Answer
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.
Write the output of the following code:
d = {'a':1, 'b':2, 'c':3}
print (d['a'])
Answer
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)
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.
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']