string to dictionary | python dictionary | data types in python | exersice in python #shorts

preview_player
Показать описание
dictionary in python
string to dictionary | python dictionary | data types in python | exersice in python #shorts

Given String - "Hello world"
Count the appearance of each alphabet and
store in a dictionary.
Expected result -
{"H":1, "e":1,"l":3,"o":2,"w":1,"r":1,"d":1}

code:
string = "hello word"

dictionary = {}

for i in string:
if i in dictionary:
continue
elif i==" ":
continue
else:
print(dictionary)

output:
{'h': 1, 'e': 1, 'l': 2, 'o': 2, 'w': 1, 'r': 1, 'd': 1}
Рекомендации по теме
Комментарии
Автор

Again inefficient code. Time complexity is O(n^2) instead of O(n).

Better for loop:
And then just remove the space from the dictionary.
for c in string:
dct[c] = dct.get(c, 0) + 1

tomasstrnad