Home > Net >  Returning number of items in dictionary
Returning number of items in dictionary

Time:04-08

I want to modify this function to return the number of items in the dictionary that begin with each letter. For example:

list= ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
print(letterCount(list))
{'I': 4, 's': 2, 'w': 2, 'm': 2, 'a': 1}

So far I can return the first letter and words, but not the number of letters that are different.

def letterCounter(wrdLst):
    output = {}
    for word in wrdLst:
        letter = word[0]
        if letter in output:
            output[letter].append(word)
        else:
            output[letter] = [word]
    return output

list = ["apple", "pear", "brown", "red"]
print(letterCounter(list))

this would return the letters instead of number: output:

{'I': ['I'], 's': ['say'], 'w': ['what'], 'm': ['mean'], 'a': ['and']}

CodePudding user response:

Don't append the word, increment a counter.

def letterCounter(wrdLst):
    output = {}
    for word in wrdLst:
        letter = word[0]
        if letter in output:
            output[letter]  = 1
        else:
            output[letter] = 1
    return output

You can also use the standard collections module.

from collections import Counter

def letterCounter(wrdLst):
    return Counter(word[0] for word in wrdLst)

CodePudding user response:

If you are cool using numpy, you can just use its unique function to do what you are trying to do. Below inside of the np.unique call, I do a list comprehension to pull the first letter off of each word and make sure it is lowercase. Then the unique function returns the unique starting letters and with return_counts enabled gives their number of occurrences.

import numpy as np

words = ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
unique, counts = np.unique([word[0].lower() for word in words], return_counts=True)

for (val, count) in zip(unique, counts):
    print (val, count)

CodePudding user response:

Another Counter way:

from collections import Counter

def letterCount(words):
    return Counter(next(zip(*words)))

words = ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
print(letterCount(words))

CodePudding user response:

Using a defaultdict will make the code more concise as follows:

from collections import defaultdict

def letterCounter(wrdLst):
    d = defaultdict(int)
    for w in wrdLst:
        d[w[0]]  = 1
    return dict(d) # return a regular dictionary
    
print(letterCounter(['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']))

Output:

{'I': 4, 's': 2, 'w': 2, 'm': 2, 'a': 1}

CodePudding user response:

You can also make the initial letters to a string and then use str.count() to make the dict:

def letter_count(wrdLst):
   s = ''
   for i in wrdLst:
      s  = i[0]
   d = {}
   for i in s:
       d[i] = s.count(i)
   return d
  • Related