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."
word = 'he'
word2 = 'he'
d1 = {}
d2 = {}
for letter in word:
if letter in d1:
d1[letter] =1
else:
d1[letter] = 1
print(d1)
#That Outputs: {'h': 1, 'e': 1}
for letter in word2:
if letter in d2:
d2[letter] =1
else:
d2[letter] = 1
print(d2)
#That Outputs {'h': 1, 'e': 1}
#That Outputs: None
#I want the outputs {'h': 2, 'e': 2}
CodePudding user response:
You can concatenate strings and use a single dictionary:
word1 = 'he'
word2 = 'he'
common_dict = {}
for letter in word1 word2:
if letter in common_dict:
common_dict[letter] = 1
else:
common_dict[letter] = 1
print(common_dict)
Also please never use a built-in name as a variable name. In your case, you used dict
as a variable name
CodePudding user response:
To merge counters dictionaries d1
and d2
:
d = d1.copy()
for k, count in d2:
if k not in d:
d[k] = 0
d[k] = count
Alternatively:
d = defaultdict(d1, int)
for k, count in d2:
d[k] = count