How to fill python dictionary while creating it

I’m searching for a way of filling a python dictionary at the same time it is created

I have this simple method that firstly creates a dictionary with all the keys at value 0 and then it reads the string again to fill it

def letter_count(word):
    letter_dic = {}
    for w in word:
        letter_dic[w] = 0
    for w in word:
        letter_dic[w] += 1
    return letter_dic

The method above should count all the occurrences of each letter in a given string

Input:

"leumooeeyzwwmmirbmf"

Output:

{'l': 1, 'e': 3, 'u': 1, 'm': 4, 'o': 2, 'y': 1, 'z': 1, 'w': 2, 'i': 1, 'r': 1, 'b': 1, 'f': 1}

Is there a form of creating and filling the dictionary at the same time without using two loops?

>Solution :

Yes it is!
The most pythonic way would be to use the Counter

from collections import Counter

letter_dic = Counter(word)

But there are other options, like with pure python:

for w in word:
    if w not in letter_dic: 
        letter_dic[w] = 0
    letter_dic[w] += 1

Or with defaultdict. You pass one callable there and on first key access it will create the key with specific value:

from collections import defaultdict

letter_dic = defaultdict(int)
for w in word:
   letter_dic[w] += 1

Leave a Reply