Home > database >  Empty Dictionary while trying to count number of different characters in Input String using a dictio
Empty Dictionary while trying to count number of different characters in Input String using a dictio

Time:11-04

I get an empty dictionary while I m trying to count number of different characters(upper case and lower case) in an given string.

Here is my code that i tried: in an if condition i put variable a =1 , to do nothing in if condition.

input_str = "AAaabbBBCC"
histogram = dict()
for idx in range(len(input_str)):
    val = input_str[idx]
    # print(val)
    if val not in histogram:
        # do nothing
        a = 1
    else:
        histogram[val] = 1

print(histogram)
#print("number of different are :",len(histogram))

here is my code output:

{}

I am expecting a output as below:

{ 'A': 1, 
  'a': 1, 
  'b': 1, 
  'B': 1,
  'C': 1
}

CodePudding user response:

If you wanted to count the number of distinct values in your string, you could do it this way

input_str = "AAaabbBBCC"
histogram = dict()

for idx in range(len(input_str)):
    val = input_str[idx]
    if val not in histogram:
        #add to dictionary
        histogram[val] = 1
    else:
        #increase count
        histogram[val]  = 1


>>> histogram
{'A': 2, 'a': 2, 'b': 2, 'B': 2, 'C': 2}
  • Related