How to fill python dictionary while creating it

Question:

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?

Asked By: DDela

||

Answers:

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
Answered By: kosciej16

You can use dictionary comprehension, e.g.

x = "leumooeeyzwwmmirbmf"
y = {l: x.count(l) for l in x}
Answered By: Matt Pitkin

You can use Counter from collections:

from collections import Counter
src = "leumooeeyzwwmmirbmf"
print(dict(Counter(src))

gives expected

{'l': 1, 'e': 3, 'u': 1, 'm': 4, 'o': 2, 'y': 1, 'z': 1, 'w': 2, 'i': 1, 'r': 1, 'b': 1, 'f': 1}
Answered By: Marcin Orlowski
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.