Praxis Praxis - 4 months ago 15
Python Question

Python - Updating dictionary values after a .count() function while iterating

I'm having a problem with counting letters in a string and then updating this value to a dictionary.

I am iterating through a dictionary of alphabet letters and using the .count() function at each pair to compare to a sentence.
The count is working and returns the number you would expect (in this case xval), however this is not updating the dictionary when I use dic[k] = xval.

Infuriatingly simple. Please offer some advice if you can.

import string

type = ("cat sat on the mat").lower()

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

print(dic)

for k, v in dic.items():
xval = type.count(k)
print(xval)
dic[k] = xval
print ("%s: %s" % (k, v))


And here is the output for completion. Many thanks.

{'m': 0, 'l': 0, 'h': 0, 'f': 0, 'd': 0, 'x': 0, 'i': 0, 's': 0, 'r': 0, 'u': 0, 'z': 0, 't': 0, 'c': 0, 'a': 0, 'q': 0, 'p': 0, 'j': 0, 'n': 0, 'g': 0, 'w': 0, 'o': 0, 'e': 0, 'k': 0, 'b': 0, 'v': 0, 'y': 0}


0
f: 0
0
q: 0
0
r: 0
1
m: 0
1
c: 0
3
a: 0
0
u: 0
0
g: 0
1
e: 0
0
d: 0
0
v: 0
1
h: 0
0
y: 0
0
k: 0
4
t: 0
0
i: 0
1
o: 0
0
w: 0
0
b: 0
1
s: 0
0
l: 0
0
j: 0
0
x: 0
0
z: 0
1
n: 0
0
p: 0

Process finished with exit code 0

Answer

You are printing k and v which do not reflect the updated dictionary.

import string

type = ("cat sat on the mat").lower()

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

print(dic)

for k in dic:
    xval = type.count(k)
    print(xval)
    dic[k] = xval
    print k, ":", dic[k]

outputs

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