Create a dictionary containing the frequency of each character in a given string
str1 = "peter piper picked a peck of pickled peppers"
freq = {}
freq2 = {}
for c in str1:
freq[c] = freq.get(c, 0) + 1
freq2 = {c: freq2.get(c, 0) + 1 for c in str1}
print(freq)
print(freq2)
Output
{'p': 9, 'e': 8, 't': 1, 'r': 3, ' ': 7, 'i': 3, 'c': 3, 'k': 3, 'd': 2, 'a': 1, 'o': 1, 'f': 1, >'l': 1, 's': 1}
{'p': 1, 'e': 1, 't': 1, 'r': 1, ' ': 1, 'i': 1, 'c': 1, 'k': 1, 'd': 1, 'a': 1, 'o': 1, 'f': 1, >'l': 1, 's': 1}
I just wanted to know why dictionary comprehension is not giving me the right answer?
When looping using the dictionary comprehension, freq2
is yet to be updated and all values are non-existent so get
returns 0
(and you add 1
so assigned value to keys is 1
to a new dictionary).
Only after the dictionary comprehension, freq2
is updated (with the dictionary created by the dictionary comprehension).
The steps are:
freq2
is emptyfreq2
empty dictionary. Then, that new dictionary is assigned to freq2