We can achieve this task using the two approaches:
Approach 1: Using the for loop
marks = {
"Bill" : 78,
"Tim" : 75,
"Steve" : 80,
"Jeff" : 79
}
to_remove = ["Tim", "Jeff"]
for name in to_remove:
if name in marks:
marks.pop(name)
print(marks)
Approach 2: Using comprehension
marks = {
"Bill" : 78,
"Tim" : 75,
"Steve" : 80,
"Jeff" : 79
}
to_remove = ["Tim", "Jeff"]
new_marks = {name:marks[name] for name in marks.keys() - to_remove}# in to_remove:
print(new_marks)
Output:
{'Bill': 78, 'Steve': 80}
Question 3 : How can we find maximum value from the dictionary?
Approach 1: Using a for loop and a temporary variable.
marks = {
"Bill" : 78,
"Tim" : 75,
"Steve" : 80,
"Jeff" : 79
}
new_keys = ["Tim", "Jeff"]
new_dict = {}
for name in new_keys:
new_dict[name] = marks[name]
print(new_dict)
Approach 2: Using dictionary comprehension.
marks = {
"Bill" : 78,
"Tim" : 75,
"Steve" : 80,
"Jeff" : 79
}
new_keys = ["Tim", "Jeff"]
new_dict = {name: marks[name] for name in new_keys}
print(new_dict)
Approach 3: Using the update method.
marks = {
"Bill" : 78,
"Tim" : 75,
"Steve" : 80,
"Jeff" : 79
}
new_keys = ["Tim", "Jeff"]
new_dict = {}
for name in new_keys:
new_dict.update({name: marks[name]})
print(new_dict)
Output:
Steve
Question 5 : Check if the value is present in the dictionary.
Given Dictionary:
marks = {"Bill" : 87, "Steve" : 85, "Jeff" : 81}
Value to check:
81
Solution:
Approach 1: Using values() method.
marks = {"Bill" : 87, "Steve" : 85, "Jeff" : 81}
value = 81
if value in marks.values():
print("Value is Present")
else:
print("Value is not Present")
Approach 2: Using for loop.
marks = {"Bill" : 87, "Steve" : 85, "Jeff" : 81}
value = 81
for i in marks:
if value == marks[i]:
print("Value is Present")
break;
else:
print("Value is not presnt")
Output:
Value is Present
Question 6 : We have 3 dictionaries of marks of marks. How can we create a single dictionary by nesting three dictionaries in the one dictionary.
Question 9 : How can we check if the dictionary is empty?
Solution:
dict1 = {}
dict2 = {1:"one", 2:"two"}
if dict1 == dict():
print("Dictionary dict1 is empty.")
if dict2 == dict():
print("Dictionary dict2 is empty.")
Output:
Dictionary dict1 is empty.
Question 9 : We have a dictionary with 9 votes for two candidates, ‘a’ and ‘b’. How can we count the number of votes each candidate has got and the winner?