Avatar of jskfan
jskfan
Flag 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:

p
The question is why I am getting the "None" ?

Thank you
Python

Avatar of undefined
Last Comment
jskfan

8/22/2022 - Mon
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.
sahil Chopra

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".
Subodh Tiwari (Neeraj)

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

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
Shalom Carmel

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
jskfan

ASKER
Thank you Guys! I will test it later