pythonlistaccumulator

Accumulating Multiple Results In a Dictionary


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?


Solution

  • 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)