'how can I get a dictionary to display 0 when something appears no times?
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
Solution 1:[1]
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.
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jinghui Ding |
| Solution 2 |
