+ 1
Explain me this code step by step
str = input() h = {} for i in str: if i not in h: h[i]=1 else: h[i]+=1 print(h) Anyone please explain me this code, it actually counts the occurrences of every letter in a word. And what's the meaning of 'h[i]'? Please explain me step by step.
3 Answers
+ 9
h[i] is used to access the value at the key 'i', in dictionary 'h'
We can also use this notation to add "key, value" or modify value to some existing key.
Look at the dictionary lesson in 'Python' Core for explanation and examples.
--------------------------------------------------------------
In easy language, it works like this:
take input from user
Create an empty dictionary to store occurences
Iterate over the alphabet in word (provided by user):
if alphabet is not present in dictionary:
add it in the dictionary
else (or if the alphabet is present in dictionary)
increase the alphabet count
print the occurance of alphabets / characters in dictionary
--------------------------------------------------------------
+ 3
Thanks a ton bro.. now I have clearly understood.