Monday, July 25, 2022

How to use a dictionary with a string?

In this post, we will use the dictionary to count the number of letters in a string that is entered by a user.
Example 1 Create a program that will ask the user to type a string and the program will show a dictionary where keys are characters of a string and values are the number of times the character is shown in a string.
Solution
USER_INPUT = input("Enter a sentence>")
Count = dict()
for a in USER_INPUT:
if a not in Count:
Count[a] = 1
else:
Count[a] += 1
print("Count = {}".format(Count))
In the previous code block, the for loop traverses the string. In each iteration if the character a is not in the dictionary a new dictionary item is created with key a and the initial value 1. If character a is already in the dictionary the Count[a] is updated. The output of the program is given below.
Enter a sentence> It always seems impossible until it's done.
Count = {'I': 1, 't': 3, ' ': 6, 'a': 2, 'l': 3, 'w': 1, 'y': 1,
's': 6, 'e': 4, 'm': 2, 'i': 4, 'p': 1, 'o': 2, 'b': 1, 'u': 1,
'n': 2, "'": 1, 'd': 1, '.': 1}

Dictionaries have a method called get which takes a key and a default value. If the key is inside the dictionary the get method will return the corresponding value. However, if the key does not exist it will return the default value.
Example 2 Create a dictionary with 4 key-value pairs and using get method search for one key-value pair that exists and one that does not.
Solution: Create empty dictionary TestScores and write 4 key-value pairs. The keys will be student names and values will be scored from 0 to 100.
TestScores = {"Anna": 70, "Tom": 86, "Lara": 65, "Sandra": 73}
Now we will search for "Lara" and "Noa" using get method.
print("TestScores.get('Lara', 0) = {}".format(TestScores.get('Lara',0)))
print("TestScores.get('Noa',0) = {}".format(TestScores.get('Noa',0)))
The output is shown below.
TestScores.get('Lara', 0) = 65
TestScores.get('Noa',0) = 0
In the next example we will apply the get method to user input program from the Example 1.
Example 3 Create a program that will ask a user to type a string and the program will show a dictionary where key-value pairs are characters from a string with a number of times the character shows in the string. In this example use get method.
Solution:
USER_INPUT = input("Enter a sentance> ")
Count = dict()
for a in USER_INPUT:
Count[a] = Count.get(a,0) + 1
print("Count = {}".format(Count))

No comments:

Post a Comment