Answer to Question #274565 in Python for Happpy

Question #274565

Write a Python program that takes a dictionary as an input from the user and then prints the average of all the values in the dictionary.

[You are not allowed to use len() and sum()]

Hint (1): For taking dictionary input

Approach(1): For taking dictionary as an input from the user, you may take the whole dictionary as a string using the input() function. Then you can use the split(), strip() functions and conditions to get the keys and values from the string. Finally, you can make the dictionary using the obtained data.

Approach(2): If the first approach seems too difficult you can create an empty dictionary and then just run a simple loop. For each iteration ask the user for a key and a value using the input() function and keep updating the dictionary with the key and value.

Hint (2): After you have a dictionary, you can use dictionary functions to get all the values from it, run loop to calculate the sum and the total number of values in the dictionary in order to find out the average.

.


1
Expert's answer
2021-12-02T06:47:25-0500
str_dict = input('Enter Dictionary in one line in format: key1:val1, key2:val2...\n')
dictionary = {}
for pair in str_dict.split(','):
	dictionary[pair.split(':')[0].strip()] = int(pair.split(':')[1].strip())
s = 0
c = 0
for val in dictionary.values():
	s += val
	c += 1
if c != 0:
	print('the average of all the values in the dictionary:', s/c)
else:
	print('the dictionary is empty')

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS