Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading