Link to home
Create AccountLog in
Avatar of jskfan
jskfanFlag for Cyprus

asked on

working with Python Dictionary

working with Python Dictionary

I have the code below :
message=input(">")
words=message.split(' ')
print (words)
emoh={
    ":)":"😂",
    ":(":"😒"
}
output=""
for word in words:
    print(word,word,word,word,word)
    print (emoh.get(word))
    output+= (emoh.get(word,word))
print (output)

Open in new window


When I run it , I get the result below:

User generated image
The question is why I am getting the "None" ?

Thank you
Avatar of pepr
pepr

That is because the word is not in dictionary. You probably want to use:
emoh.get(word, word)

Open in new window

also in the first print. The first word is used as a key to the dictionary. If it is not in the dictionary, the second value is used as a default. So, or the word is translated, or you get the same word -- as you do it correctly in the next command.

A side note: Python strings are immutable. This means that they cannot be modified. This means that the output += emoh.get(word, word) always constructs a new string and throws away the older content. That can be very inefficient if you use large texts.
in this code, you have used get keyword for getting the value of a key from the dictionary. if a key is present in the dictionary then this will give you value else it will give you none.
in this code you have used "print(emoh.get(word))" here it is giving you "None" because that word is not present in "emoh".
As other two experts mentioned, you are getting None because the keys you are trying to find in the dictionary don't exist.

The keys in the dictionary which exist are ":)" and ":(" whereas you are trying to find the keys "aaaa" and "bbbb" assuming your input was "aaaa bbbb" which don't exist at all in the dictionary.

Assuming your input is "aaaa bbbb" or two words separated by a space, the following code will give you the desired output.

message=input(">")
words=message.split(' ')
print (words)

emoh={
    words[0]:"😂",
    words[1]:"😒"
}
output=""
for word in words:
    print(word,word,word,word,word)
    print (emoh.get(word))
    output+= (emoh.get(word,word))
print (output)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Shalom Carmel
Shalom Carmel
Flag of Israel image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of jskfan

ASKER

Thank you Guys! I will test it later