Computer Science
Find the errors:
text = "abracadbra"
counts = {}
for word in text :
counts[word] = counts[word] + 1
Python Dictionaries
9 Likes
Answer
Output
KeyError: 'a'
Explanation
The line counts[word] = counts[word] + 1 will cause a KeyError because we are trying to access a key word of an empty dictionary. As the key is not present in dictionary counts, hence a KeyError is generated.
Answered By
3 Likes
Related Questions
Predict the output:
list1 = [2, 3, 3, 2, 5,3, 2, 5, 1,1] counts = {} ct = 0 lst = [] for num in list1: if num not in lst: lst.append(num) counts[num] = 0 ct = ct+1 counts[num] = counts[num]+1 print(counts) for key in counts.keys(): counts[key] = key * counts[key] print(counts)Create a dictionary 'ODD' of odd numbers between 1 and 10, where the key is the decimal number and the value is the corresponding number in words.
Perform the following operations on this dictionary :- Display the keys
- Display the values
- Display the items
- Find the length of the dictionary
- Check if 7 is present or not
- Check if 2 is present or not
- Retrieve the value corresponding to the key 9
- Delete the item from the dictionary corresponding to the key 9
my_dict = {} my_dict[(1,2,4)] = 8 my_dict[[4,2,1]] = 10 print(my_dict)Predict the output:
fruit = {} L1 = ['Apple', 'banana', 'apple'] for index in L1 : if index in fruit: fruit[index] += 1 else : fruit[index] = 1 print(len(fruit)) print(fruit)