Create a dictionary named letter_counts that contains each letter and the number of times it occurs in string1. Challenge: Letters should not be counted separately as upper-case and lower-case. Intead, all of them should be counted as lower-case.

Respuesta :

Answer:

  1. letter_counts = {}
  2. string1 = "I have a dream"
  3. string1 = string1.lower()
  4. for x in string1:
  5.    if(x == " "):
  6.        continue  
  7.    if x not in letter_counts:
  8.        letter_counts[x] = 1
  9.    else:
  10.        letter_counts[x] += 1
  11. print(letter_counts)

Explanation:

The solution is written in Python 3.

Firstly create a letter_count dictionary (Line 1)

Next, create a sample string and assign it to string1 variable and convert all the characters to lowercase using lower method (Line 4).

Create a for loop to traverse through each character in string1 and check if the current character is a single space, just skip to the next iteration (Line 7 -8). If the current character is not found in letter_counts dictionary, set the initial count value 1 to x property of letter_counts. Otherwise increment the x property value by one (Line 9 -12).

After completion of loop, print the letter_count dictionary. We shall get the sample output {'i': 1, 'h': 1, 'a': 3, 'v': 1, 'e': 2, 'd': 1, 'r': 1, 'm': 1}