Hello, developer!
Have you tried to upgrade your calculator? I encourage you modify codes and execute more codes as possible as you can. Then you can learn it more clearly and make better codes.
Today, we will learn the "Dicitionaries". "Dictionary" feature enables you can use predefined matched values in dictionary.
Here is declaration of dictionary feature and an example.
Dictionary declaration and form
dictionery_name = { "value_1": "matched_value_1", "value_2": "matched_value_2", "value_3": "matched_value_3",...}
dictionery_name = { value_1: "matched_value_1", value_2: "matched_value_2", value_3: "matched_value_3",...} # value_1, value_2, ... can be numbers like 0, 1, 2,...
Example of dictionary
monthConversions = { "Jan":"January", "Feb":"February", "Mar": "March"}
You can call matched value by calling dictionary by below form.
Dictionary calling form
dictionary_name.get("value")
If there is no matched value in dictionary, it returns "None" message instead error message.
If you want to setting up the default none-matched value message, please use below form.
Setup of default none-matched return message
dictionary_name.get("value", "Default none-matched return message")
I showed full exercise codes and execution result as following.
monthConversions = {
"Jan":"January",
"Feb":"February",
"Mar": "March",
"Apr": "April",
"May": "May",
"Jun": "June",
"Jul": "July",
"Aug": "August",
"Sep": "September",
"Oct": "October",
"Nov": "November",
"Dec": "December"
}
print(monthConversions.get("Jul", "Not a valid key!"))
monthConversions2 = {
0:"January",
1:"February",
2: "March",
3: "April",
4: "May",
5: "June",
6: "July",
7: "August",
8: "September",
9: "October",
10: "November",
11: "December"
}
print(monthConversions2.get(12, "Not a valid key!"))
Can you see the same result? Great job! Now you can use "Dictionaries" feature in the Python. It will be helpful while you get abbreviations or acronyms input from users.
Alright, see you on next post, developer! 😊
No comments:
Post a Comment