CBSE Class 12 Computer Science Question 51 of 57

Review of Python Basics — Question 51

Back to all questions
51
Question

Question 46

Write a Python program to count number of items in a dictionary value that is a list.

Solution
my_dict = eval(input("Enter the dictionary: "))
total_count = 0
for value in my_dict.values():
    if type(value) is list:
        total_count += len(value)
print("Total number of items in lists within the dictionary:", total_count)
Output
Enter the dictionary: {'l1': [1, 2, 3, 4], 'l2': 'Apple', 'l3': [True, False], 'l4': 'Orange'}         
Total number of items in lists within the dictionary: 6
Answer

my_dict
=
eval
(
input
(
"Enter the dictionary: "
))
total_count
=
0
for
value
in
my_dict
.
values
():
if
type
(
value
)
is
list
:
total_count
+=
len
(
value
)
print
(
"Total number of items in lists within the dictionary:"
,
total_count
)
Output
Enter the dictionary: {'l1': [1, 2, 3, 4], 'l2': 'Apple', 'l3': [True, False], 'l4': 'Orange'}
Total number of items in lists within the dictionary: 6