Accumulating Multiple Results In a Dictionary

565 views Asked by At

The question as below: Create a dictionary called char_d from the string stri, so that the key is a character and the value is how many times it occurs.

this is the code i tried:

stri = "what can I do"
char_d={}
lst=stri.split()
for wrd in lst:
    for c in wrd:
        if c not in char_d:
        char_d[c]=0
    char_d[c]+=1

the output i get is:

[('h', 1), ('o', 1), ('c', 1), ('t', 1), ('n', 1), ('d', 1), ('I', 1), ('a', 2), ('w', 1)]

the expected value should include: (' ',3)

i think the value should be including the space but how we do it?

3

There are 3 answers

0
kyc12 On BEST ANSWER

What you proposed works. You can use get method of dictionary to be more pythonic.

stri = "what can I do"
char_d={}
#lst=stri.split()
#for wrd in stri:
for c in stri:
   char_d[c] = char_d.get(c, 0) + 1

get(c, 0) will return 0 if c does not exist in the dict.

You can also use Counter from collections.

char_d = Counter(stri)
2
GEH_L On
stri = "what can I do"
char_d={}
#lst=stri.split()
#for wrd in stri:
for c in stri:
   if c not in char_d:
      char_d[c]=0
   char_d[c]+=1

I think i found a solution but will appreciate it if there is any further explaination.

0
kklitzing On

The reason your dictionary does not contain the whitespace character is because you used the .split() method.

lst=stri.split()

Because there are no parameters between the parentheses, the split() method used the default (the whitespace character) to divide the string into an ordered sequence and returns that as a list object.

['what', 'can', 'I', 'do']

You can pass any string (or object that evaluates to string) to the method, a la:

lst=stri.split('a')

This will split stri by the character 'a' instead, yielding:

['wh', 't c', 'n I do']

In every case, the demarcating character(s) that the split method uses is lost in the process.