1

I want to make a dictionary using a string, and count the words of that string. This is what I've done but it's giving me an error!

book_text = "if it exists it should print"
for word in book_text:
    word = book_text.split(" ")
print(word)

dictionary = {}
for i in word:
    dictionary.values(i)
    dictionary.keys(word.count(i))
    print(dictionary)

Error says values takes more than one element

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Please give an example, how do you want your dictionary to look like? – oreopot Oct 12 '19 at 03:08
  • 2
    Are you looking for [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter)? – wjandrea Oct 12 '19 at 03:13
  • Possible duplicate of [Convert two lists into a dictionary](https://stackoverflow.com/q/209840/1092820) (I originally flagged as a duplicate of a different question, but this may be more appropriate) – Ruzihm Oct 12 '19 at 03:16

1 Answers1

0

You can use setdefault method to set a key's value to 0 if its not present. If the key is already is present, it will return the value.

Initial Variables

s = 'I want to make a dictionary using a string and count the words of that string'
a = [1, 2, 3, 2, 3]
d = {}

Different ways of building your dictionary

for xx in s:
    d[xx] = 1 + d.get(xx, 0)

print(d)

Also if you don't want to use the library, then you can do in this way.

for xx in s:  #same way we can use a
    if xx not in d:
        d[xx] = 1
    else:
        d[xx]+ = 1

Again we can use Counter which is faster.

from collections import Counter
s = list(s)
print(Counter(s))
sam
  • 1,819
  • 1
  • 18
  • 30
Tedd8989
  • 72
  • 5