Reputation: 25
I need to implement a function on a dictionary.
Variables:
The existing dictionary has the letters I have to play and the value represent the frequency of the letter. eg. {'a': 1, 'n': 2, 'd': 1, 'e': 1}
The word represent a word constructed with those letters. eg. 'and'
I need to implement a code which return a dictionary with all letters remaining (that are not in the word) and their values(frequency). Value should be zero if the letter was used.
I have wrote this code:
dic = {'a': 1, 'n': 2, 'd': 1, 'e': 1}
word = 'and'
newdic = {}
for keys in dic:
if keys not in word:
newdic[keys] = newdic.get(keys,0) + 1
print(newdic)
the output I got is: {'e': 1}
but the Expected output should be: {'a': 0, 'n': 1, 'd': 0, 'e': 1}
can you please advise? thanks
Upvotes: 1
Views: 69
Reputation: 440
dic = {'a': 1, 'n': 2, 'd': 1, 'e': 1}
word = 'and'
newdic = {}
for keys in dic:
if keys not in word:
newdic[keys] = newdic.get(keys, 0) + 1
else:
newdic[keys] = dic.get(keys, 0) -1
print(newdic)
I think this is what you were looking for. See the for-loop statement and the else
part added.
Upvotes: 1
Reputation: 443
This can help. Add an else
statement for the keys
that are in the word [in this case, "and"
].
dic = {'a': 1, 'n': 2, 'd': 1, 'e': 1}
word = 'and'
newdic = {}
for keys in dic.keys():
if keys not in word:
newdic[keys] = dic[keys]+1
else:
newdic[keys] = dic[keys]-1
print(newdic)
Upvotes: 1