How to Spell out Number Using Dictionary in Python

Here is a Python program that spells out a number using a dictionary.

How it works is – if you enter numeric ‘1’, it displays ‘one’ as a character.

Python supports three types of compound data types.

Those are List, Tuple, and Dictionary. Out of these, I used a dictionary-type to achieve this.

What is python dictionary?

You can create an empty dictionary with empty curling braces. It supports data of type key/value pairs.

my_dictionary = {}

Here is a dictionary with data of two key-value pairs.

my_dictionary = {"name" : "Srini", "age" : 20}

Further to, you can get data from a dictionary by giving the key value.

my_dictionary["name"] ==> it will display Srini

Here is screen shot of the results

As said, with the key, you can print its value. The same concept I used to write the program.

How to display dictionary data using key

Here is python logic to spell out a number

## This program spells out the number
my_input = input("Enter number from 1 to 4: ")
my_dict_mapping = {
    "1" : "One",
    "2" : "Two",
    "3" : "Three",
    "4" : "Four"
for i in my_dict_mapping:
    if i == my_input:   
        print (my_dict_mapping[i])
        print ("Mind your entry!!")

The output after you execute the program

Python program how to use dictionary

So, the output is one for the input ‘1’ that you entered.

You can try the same program in your python interpreter too.

If the input value does not match the dictionary key-value, it will display as “Mind your entry!!”

Related posts

Get new content delivered directly to your inbox.

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.