Gregory Rubinstein
Gregory Rubinstein

Reputation: 101

count upper case and lowercase separately in a dictionary in Python

I was trying to do the following exercise: Consider the sentence 'Jim quickly realized that the beautiful gowns are expensive'. Create a dictionary count_letters with keys consisting of each unique letter in the sentence and values consisting of the number of times each letter is used in this sentence. Count upper case and lower case letters separately in the dictionary.

Below is my code, and I think it's doing what the exercise is asking, but for some reason it still says that I did not do it right. Any ideas, anyone?

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
cnt_lowercase = 0
cnt_uppercase = 0
#write your code here!
for c in sentence:
    if c.islower():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_lowercase += 1
    if c.isupper():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_uppercase += 1
print(str(cnt_lowercase))
print(str(cnt_uppercase))
print(count_letters)

Upvotes: 3

Views: 7708

Answers (11)

guantai dickson
guantai dickson

Reputation: 1

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
for s in sentence:
    if (s.isupper()):# This checks upper case letters
        if (s not in count_letters.keys()):# This check whether the letter is in dict
            count_letters[s] = 1# if not in dict counts as the first
        else:
           count_letters[s] += 1 #if letter present it increments by 1
    else:
        if (s.islower()):
            if(s not in count_letters.keys()):
                count_letters[s] = 1
            else:
                count_letters[s] += 1
                
print(count_letters)

Upvotes: 0

stephen mbelenga
stephen mbelenga

Reputation: 7

import string
alphabet = string.ascii_letters

sentence = 'Jim quickly realized that the beautiful gowns are expensive'

count_letters = {}

write your code here!

count_letters_upper = dict([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet.upper()])

count_letters_lower = dict([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet.lower()])

print(count_letters_upper)

print(count_letters_lower)

Output:

{'J': 1}

{'h': 2, 'k': 1, 'o': 1, 'v': 1, 'r': 2, 'y': 1, 'n': 2, 'e': 8, 'p': 1, 'c': 1, 's': 2, 'a': 4, 'b': 1, 'g': 1, 'x': 1, 'i': 5, 'w': 1, 'd': 1, 'u': 3, 'z': 1, 'q': 1, 't': 4, 'm': 1, 'l': 3, 'f': 1}

Upvotes: -1

Vishwa Mohan Tiwari
Vishwa Mohan Tiwari

Reputation: 1

sentence = 'Jim quickly realized that the beautiful gowns are expensive'

count_upper = {}

count_lower = {}

count_letters = {}

# write your code here!

for c in sentence:

    if c.isupper():

        if (c in count_upper):

            count_upper[c] +=1

        else:

            count_upper[c] =1

    if c.islower():

        if (c in count_lower):

            count_lower[c] +=1

        else:

            count_lower[c] =1


count_letters = {**count_upper, **count_lower} ;

print(count_letters)

Upvotes: 0

Aman Gupta
Aman Gupta

Reputation: 757

This is solution for above question. You can modify according to your need.

alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = dict()

for letter in sentence:
    if letter in alphabet:
        if letter in count_letters.keys():
            count_letters[letter] += 1
        else:
            count_letters[letter] = 1

print(list(count_letters.values())[2])
print(list(count_letters.values())[7])

Upvotes: 0

Van Nguyen
Van Nguyen

Reputation: 1

This is my suggest with list comprehensions

Note: Count upper case and lower case letters separately in the dictionary.

sentence = 'Jim quickly realized that the beautiful gowns are expensive'

alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

count_letters_upper = ([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet if letter.isupper()])

count_letters_lower = ([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet if letter.islower()])

Upvotes: 0

Bellash
Bellash

Reputation: 8184

You can use the called list comprehensions to accomplish this

 alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
 sentence = 'Jim quickly realized that the beautiful gowns are expensive'
 counts = dict([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet]) 

Upvotes: 1

LeKhan9
LeKhan9

Reputation: 1350

Delegating the cache building and counting logic to separate functions:

   def build_cache(sentence):
        char_to_count_cache = {}
        for ch in sentence:
            if ch.isalnum():
                char_to_count_cache[ch] = char_to_count_cache.get(ch, 0) + 1

        return char_to_count_cache

    def get_upper_and_lower_counts(char_to_count_cache):
        num_lower_letters, num_upper_letters = 0, 0
        for k in char_to_count_cache:
            if k.islower():
                num_lower_letters += 1
            else:
                num_upper_letters += 1

        return num_lower_letters, num_upper_letters

Driver:

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
char_to_count_cache = build_cache(sentence)
num_lower_letters, num_upper_letters = get_upper_and_lower_counts(char_to_count_cache)

total_letters = len(char_to_count_cache)

print total_letters
print num_lower_letters
print num_upper_letters

Output:

26 
25 
1 

Upvotes: 0

khachik
khachik

Reputation: 28693

from collections import Counter


count_letters = Counter('Jim quickly realized that the beautiful gowns are expensive')
# this gives a dictionary of character -> count

# if you need to skip spaces/punctuations (you probably do), use this
count_letters = Counter(c for c in 'Jim quickly realized that the beautiful gowns are expensive' if c.isalpha())

Upvotes: 1

carlos_fab
carlos_fab

Reputation: 18

You should have not a dictionary of dictionaries, but a dictionary where the count occurrences of a char are returned directly, what means that when you type count_letters['J'], for example, you get 1 as output.

In your code, when I type count_letters['J'] I get {'J': 1} as output.

Here is how I would write this code:

sentence = 'Jim quickly realized that the beautiful gowns are expensive'

count_letters = {}
cnt_lowercase = 0
cnt_uppercase = 0

# iterate over all chars in the sentence string
for char in sentence:
    # check if the char is lowercase
    if char.islower():
        cnt_lowercase += 1
    # check if the char is upper case
    elif char.isupper():
        cnt_uppercase += 1

    # count occurrence of each char in sentence string
    b = count_letters.get(char, 0)
    count_letters[char] = b + 1


# check the output
print(count_letters)

And you get this output:

{'J': 1, 'i': 5, 'm': 1, ' ': 8, 'q': 1, 'u': 3, 'c': 1, 'k': 1, 'l': 3, 'y': 1, 'r': 2, 'e': 8, 'a': 4, 'z': 1, 'd': 1, 't': 4, 'h': 2, 'b': 1, 'f': 1, 'g': 1, 'o': 1, 'w': 1, 'n': 2, 's': 2, 'x': 1, 'p': 1, 'v': 1}

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

The problem of is that count_letters is a dictionary where the keys are the letters and the values are dictionaries with the count of that letter, in the exercise you were asked to compute

values consisting of the number of times each letter is used in this sentence.

Your code:

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
cnt_lowercase = 0
cnt_uppercase = 0
for c in sentence:
    if c.islower():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_lowercase += 1
    if c.isupper():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_uppercase += 1
print(count_letters)

Output

{'u': {'u': 3}, 'g': {'g': 1}, 'q': {'q': 1}, 'l': {'l': 3}, 'o': {'o': 1}, 'm': {'m': 1}, 'f': {'f': 1}, 'k': {'k': 1}, 'z': {'z': 1}, 'w': {'w': 1}, 'a': {'a': 4}, 'n': {'n': 2}, 'c': {'c': 1}, 'y': {'y': 1}, 'r': {'r': 2}, 'b': {'b': 1}, 'h': {'h': 2}, 'd': {'d': 1}, 'e': {'e': 8}, 'i': {'i': 5}, 'v': {'v': 1}, 'p': {'p': 1}, 's': {'s': 2}, 'x': {'x': 1}, 'J': {'J': 1}, 't': {'t': 4}}

The value of 'u' for instance is {'u': 3}. You can fix it adding the following line:

count_letters = { k : v[k] for k, v in count_letters.items()}
print(count_letters)

Output (with the new line)

{'m': 1, 'c': 1, 'f': 1, 'b': 1, 'q': 1, 'd': 1, 'o': 1, 'g': 1, 'k': 1, 'r': 2, 'z': 1, 'v': 1, 'u': 3, 'l': 3, 'y': 1, 'p': 1, 's': 2, 'e': 8, 'x': 1, 'i': 5, 'w': 1, 'h': 2, 'n': 2, 'J': 1, 'a': 4, 't': 4}

Explanation

The added line is known as a dictionary comprehension. Is equivalent to:

d = {}
for k, v in count_letters.items():
    d[k] = v[k]
count_letters = d

Upvotes: 0

Zito Relova
Zito Relova

Reputation: 1041

Your dictionary nests other dictionaries which should not be the case

eg.

{'u': {'u': 3}}

should be just

{'u': 3}

I simplified your code and it should work now:

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
cnt_lowercase = 0
cnt_uppercase = 0

for c in sentence:
    if (c in count_letters):
        count_letters[c] += 1
    else:
        count_letters[c] = 1

cnt_lowercase = len([i for i in count_letters.keys() if i.islower()])
cnt_uppercase = len([i for i in count_letters.keys() if i.isupper()])

print(count_letters)
print(cnt_lowercase)
print(cnt_uppercase)

Upvotes: 0

Related Questions