Home > front end >  how can I get a dictionary to display 0 when something appears no times?
how can I get a dictionary to display 0 when something appears no times?

Time:03-26

I want to search a list of strings for the letter a and create a dictionary that shows how many times it appeared. What I have now does this except when a doesn't appear it returns an empty dictionary. I want it to return {a: 0}. Here's what I have now in a function where its indented properly. what can i change in what i have now so that the created dictionary is {a:0}

list_strings = (["this","sentence"]
result ={}
for letter in list_strings:
    list_strings = list_strings.lower()
    for letter in letters:
        if letter == "a":
            if letter not in result:
                result[letter] = 0
            result[letter]=result[letter]   1
return result 

CodePudding user response:

You can put {'a': 0} in the result ahead of time:

result = {'a': 0}

And then do the next loop If you want to count every letter in list of words, the defaultdict is useful.

from collections import defaultdict

list_strings = ["this", "sentence", "apple"]
result = defaultdict(int)
result.update({'a': 0})
for word in list_strings:
    for letter in word:
        result[letter]  = 1

print(result)
print(result.get('t', 0))
print(result.get('a', 0))

After that, you can take value by function: get, the second parameter is optional, if element not in dictionary, get will return the second parameter.

CodePudding user response:

There are some errors in the posted code.

Guess what you need is to count the number of "a"s in all the strings in list_strings and store it in a dictionary. If there are no "a"s you need to be dictionary value for "a" to be 0.

You can initialize dictionary value "a" to zero at the beginning. I have corrected errors and do this in the below code.

list_strings = (["this","sentence"])
result ={}
result["a"] = 0
for string in list_strings:
    string = string.lower()
    for letter in string:
        if letter == "a":
            result[letter]=result[letter]   1


print(result)

If you need to count other characters you can create the initial dictionary as follows.

d1 = dict.fromkeys(string.ascii_lowercase, 0)

CodePudding user response:

You could collections.Counter to count all the letters and then use the get function on the Counter dictionary (to return 0 as the default)

>>> from collections import Counter
>>> list_strings = ["this","sentence"]
>>> c = Counter()
>>> for string in list_strings:
    c.update(string)

    
>>> c
Counter({'e': 3, 't': 2, 's': 2, 'n': 2, 'h': 1, 'i': 1, 'c': 1})
>>> c.get('a', 0)
0
  • Related