maria poscoliero
maria poscoliero

Reputation: 25

How to re-assign value to a dictionary based on

I need to implement a function on a dictionary.

Variables:

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

Answers (2)

emendez
emendez

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

Merci Dieu KIMPOLO
Merci Dieu KIMPOLO

Reputation: 443

This can help. Add an elsestatement 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

Related Questions