I’m creating a program that counts letters. I created two dictionaries that both have the same word and, because they are the same exact word, both have the same counter. I want to know how to merge the two dictionaries so that it updates the counters as well, but I consistently receive the result “NONE.”
JavaScript
x
30
30
1
word = 'he'
2
word2 = 'he'
3
d1 = {}
4
d2 = {}
5
6
for letter in word:
7
if letter in d1:
8
d1[letter]+=1
9
else:
10
d1[letter] = 1
11
print(d1)
12
13
#That Outputs: {'h': 1, 'e': 1}
14
15
16
for letter in word2:
17
if letter in d2:
18
d2[letter]+=1
19
else:
20
d2[letter] = 1
21
print(d2)
22
23
#That Outputs {'h': 1, 'e': 1}
24
25
26
27
#That Outputs: None
28
29
#I want the outputs {'h': 2, 'e': 2}
30
Advertisement
Answer
You can concatenate strings and use a single dictionary:
JavaScript
1
11
11
1
word1 = 'he'
2
word2 = 'he'
3
4
common_dict = {}
5
for letter in word1 + word2:
6
if letter in common_dict:
7
common_dict[letter] += 1
8
else:
9
common_dict[letter] = 1
10
print(common_dict)
11
Also please never use a built-in name as a variable name. In your case, you used dict
as a variable name