Advertisement
acclivity

pyCreateDictionaries

Sep 3rd, 2022
1,019
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.52 KB | None | 0 0
  1. sentence = "hello, this is a sentence"
  2.  
  3. # method 1 using get()
  4. mydict= {}
  5. for ch in sentence:
  6.     ctr = mydict.get(ch, 0)
  7.     mydict[ch] = ctr + 1
  8. print(mydict)
  9. # ------------------------
  10.  
  11. # method 2 not using get()
  12. mydic2 = {}
  13. for ch in sentence:
  14.     if ch in mydic2:
  15.         mydic2[ch] = 1 + mydic2[ch]
  16.     else:
  17.         mydic2[ch] = 1     
  18. print(mydic2)
  19. # -------------------------)
  20.  
  21. # method 3 using set() and count()
  22. mydic3 = {}
  23. aset = set(sentence)
  24. for ch in aset:
  25.     ctr = sentence.count(ch)
  26.     mydic3[ch] = ctr   
  27. print(mydic3)
  28.    
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement