Computer Science
What will be the output of the following code snippet ?
my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
my_dict[(1,2)] = 12
sum = 0
for k in my_dict:
sum += my_dict[k]
print(sum)
print(my_dict)
Python
Python Dictionaries
7 Likes
Answer
30
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}
Working
- An empty dictionary named
my_dict
is initialized. my_dict[(1,2,4)] = 8, my_dict[(4,2,1)] = 10, my_dict[(1,2)] = 12
these lines assign values to the dictionarymy_dict
with keys as tuples. Since tuples are immutable, so they can be used as keys in the dictionary.- The
for
loop iterates over the keys of the dictionarymy_dict
. Inside the loop, the value associated with each key k is added to the variablesum
. sum
andmy_dict
are printed.
Answered By
2 Likes
Related Questions
Write a method in python to display the elements of list thrice if it is a number and display the element terminated with '#' if it is not number.
For example, if the content of list is as follows :
List = ['41', 'DROND', 'GIRIRAJ', '13', 'ZARA']
The output should be
414141
DROND#
GIRIRAJ#
131313
ZAR#Name the function/method required to
(i) check if a string contains only uppercase letters.
(ii) gives the total length of the list.
Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after the area code and the next three numbers. For example, 017-555-1212 is a legal input. Display if the phone number entered is valid format or not and display if the phone number is valid or not (i.e., contains just the digits and dash at specific places.)
Write a program that should prompt the user to type some sentence(s) followed by "enter". It should then print the original sentence(s) and the following statistics relating to the sentence(s) :
- Number of words
- Number of characters (including white-space and punctuation)
- Percentage of characters that are alphanumeric
Hints
- Assume any consecutive sequence of non-blank characters is a word.