Python Data Types

Python Data Type – Dict

Python supports another data type called dict, which is short for dictionary. This data type is also a list of items just a list or a tuple, except that each item (called a key) in the dict has an associated value

Let us suppose you have four friends named Robert, Kathy, Michael, and Steve. These four names can be put in a list data type as in the statement below.

>>> friends = [‘robert’, ‘kathy’, ‘michael’, ‘steve’]

Now suppose the program you are writing also needs to specify the ages of each of your friends.  Robert is 8 years old; Kathy is 7, Michael is 7 years old, and Steve is 9 years old. So how do you associate the name of each of your friends with their ages? Dict data type helps us do it as follows:

PROGRAM EXAMPLE: DICT DATA TYPE KEY:VALUE PAIR EXAMPLE

>>> friends = {‘robert’ : ‘7’, ‘ kathy’ : ‘7.5’, ‘michael’ : ‘8’, ‘steve’ : ‘9’}

Notice that each name is associated with a value (age in this example).  The name and the value are separated by a colon (:).  Each name:value pair is separated by a comma from the next name:value pair. The name and age are individually enclosed in single quotes. The whole list of name:value pairs are enclosed in curly brackets like {….}, also called braces. 

We called the pair name:value pair. Python refers to this pair as key:value pair.

Thus, the dictionary is an unordered set of key:value pairs. Keys need to be immutable type like strings and numbers.

Here is another example of dict data type.  Here, the keys are ‘Alabama’ and ‘Alaska’. And the corresponding values are the state capitals, ‘Montgomery’ and ‘Juneau’. Let’s define a dict data type variable, named state_capitals, The statement below shows how it would be done.

PROGRAM EXAMPLE: DICT DATA TYPE KEY:VALUE PAIR ANOTHER EXAMPLE

>>> state_capitals = {‘Alabama’: ‘Montgomery’, ‘Alaska’: ‘Juneau’}

Why Use dict Data Type

In our example of friends name:age pairs, the dictionary list is small. Therefore, it is easy to find any friend’s age manually by investigating the dictionary statement.

What if the list has 200 names or a thousand names? In such a case, it would be a little time-consuming to manually find out the age corresponding to a name. 

The dictionary data type is used for storing a value for an associated key and extracting the value from the specified key.

Indexing in Dictionary Data Type

Just as you can use indexing in strings, lists, and tuples data types, we can use the index in dictionaries data types as well. As you learned earlier in this chapter, lists, tuples, and strings are indexed by the position of the item in the strings, lists, or tuples. The first item on the list, string, or tuple has an index of 0, the second item on the list has an index of 1, and so on.  Dictionaries, on the other hand, are indexed by the keys. You use the key as the index to find the value for that key

Find the Value of Any Key in a Dictionary

In the program below, we define a dictionary data type of all the planets in our solar system in the form {planet name: distance}. Now, let us suppose you want to find the distance of planet Earth from the Sun.  As described earlier, you will use the key (planet name) as the index to find the value (planet distance). Note that the key is specified in square brackets [].

PROGRAM EXAMPLE: USE CASE OF dict DATA TYPE
>>> # dict data type usage
>>> # Define a dicr data type called 'planet'		    
>>> planet_distance_from_Sun = {'Mercury' :'37 million miles', 'Venus' : '65 million miles', 'Earth' : '93 million miles', 'Mars' : '140 million miles', 'Jupiter' : '484 million miles', 'Saturn' : '884 million miles', 'Uranus' : '1786 million miles', 'Neptune' : '2,780 million miles'}
>>> print(planet_distance_from_Sun['Earth'])
93 million miles
>>> print(planet_distance_from_Sun['Uranus'])
1786 million miles
>>> print(planet_distance_from_Sun['Mars'])
140 million miles
>>>

How to Create an Empty dictionary

If you want to create an empty dictionary, use a pair of braces with nothing within the braces. A pair of braces creates an empty dictionary: {}.

PROGRAM EXAMPLE: HOW TO CREATE AN EMPTY DICTIONARY
>>> my_dictionary = {}
>>> my_dictionary
{}
>>> # Now use the print statement to find what is in the directory.
>>> print(my_dictionary)
{}
>>>

Delete a key:value Pair in Dictionary

Since the dict data type is mutable, we can delete a key:value pair with the del statement.

Let’s refer back to the “friends” dictionary. The program below deletes the item “steve” from the “friends” dictionary.

PROGRAM EXAMPLE: DELETE A KEY:VALUE PAIR IN DICTIONARY
>>> friends ={'robert' : '7', 'kathy' : '7.5', 'michael' : '8', 'steve' : '9'}
>>> friends
{'robert': '7', 'kathy': '7.5', 'michael': '8', 'steve': '9'}
>>> del friends['steve']
>>> friends # Check to see if ‘steve’ got deleted.
{'robert': '7', 'kathy': '7.5', 'michael': '9'}
>>>

Change a Value in the Dictionary

Going back to the “friends” program, suppose Michael’s birthday was just around the corner when you wrote the program.  Therefore, Michael is not 8, but he is 9 years old now. The program is updated by using “michael” as the key and specifying the corresponding value as “9”.

PROGRAM EXAMPLE: CHANGE A VALUE IN DICTIONARY DATA TYPE
>>> friends ={'robert' : '7', 'kathy' : '7.5', 'michael' : '8', 'steve' : '9'}
>>> friends
{'robert': '7', 'kathy': '7.5', 'michael': '8', 'steve': '9'}
>>> friends['michael'] = '9'
>>> # Now check if michael's age got changed to 9.
>>> friends
{'robert': '7', 'kathy': '7.5', 'michael': '9', 'steve': '9'}
>>>

Note the last line in the program shows Michael is 9.

Converting Python Data Type From One Type to Another Type

You have seen that Python has many different data types: integer, float, string, list, tuple, and dictionary. There are instances where you need to convert the data type from one type to another.

Let us consider a program where we input data from the keyboard. 

In the example below, program statement 1) asks you to enter your sister’s age using the input()  function. Python stores this value you enter in the variable “sister_age”.

Statement 2) asks you to enter your age. The program will store the value you enter in the variable “your_age”.

Statement 3) adds the values of “sister_age” and “your_age” and stores it a variable “age_addition”.

Statement 4) prints the value contained in the variable “age_addition”.

Statement 5) has the result of the addition of the two ages and the result is 83.

You had entered “your_age” as 8 and “sister_age” as 3. The result (83) produced by the program is wrong.

Let us investigate why the program produced the wrong result.

PROGRAM EXAMPLE: WHY WE NEED TO CHANGE DATA TYPE
>>> sister_age = input('Enter your sister age: ') #1)
Enter your sister age: 3
>>> your_age = input('Enter your age: ')  #2)
Enter your age: 8
>>> age_addition = your_age + sister_age  #3)
>>> print(age_addition)                   #4)
83                                        #5)
>>> 

The program says the sum of ages (8 + 3) = 83.  That is wrong.  We would expect the answer to be 8 + 3 = 11.

Can you guess what happened?

The following is what happened 

Python treats all inputs from the keyboard as string variables.  So, “your_age” and “sister_age” are treated as string variables.  Therefore, Python treats the numbers 8 and 3 you entered from the keyboard as string variables. You might also recall that when you add string variables using the ‘+’ symbol, the program concatenates the two string variables. So, the program concatenated two string variables “your_age” (8) and “sister_age” (3), and produced the result = 83. 

How to Fix This Discrepency

This brings us to the reason why we may need to change a variable data type in some instances. We intended that the numbers we entered from the keyboard were integers.  So, we will convert the string variables entered from the keyboard to integer variables before we do the addition as shown in the program below.

In order to convert a variable to an integer type, you need to type the following statement

>>>int(x)

The above statement int(x) will convert variable ‘x’ to a plain integer (a whole number with no decimal part).

In the program below, the statement 1)

>>> age_addition = int(your_age) + int(sister_age)

converts string variable ‘your_age’ and string variable ‘sister_age’ to integer int type.

PROGRAM EXAMPLE: DATA TYPE CONVERSION
>>> sister_age = input('Enter your sister age: ')
Enter your sister age: 3
>>> your_age = input('Enter your age: ')
Enter your age: 8
>>> age_addition = your_age + sister_age
>>> print(age_addition)
83
>>> # Change string variable data type to integer before adding them.
>>> age_addition = int(your_age) + int(sister_age) #1)
>>> print(age_addition)
11
>>>

In the above example, ‘int‘ before “your_age” changes the “your_age” data type from string to data type integer. Similarly for int(sister_age).

With this data type conversion, the program is able to add the ages correctly.

Data Type Conversion – Another Way

There is another way to make sure that Python treats the inputs from the keyboard as integers, and not as string data type.

The program example below shows how to change data type by putting ‘int‘ before the ‘input‘ statement. Whatever you enter from the keyboard is now treated as an integer, and not as a string.

PROGRAM EXAMPLE: DATA TYPE CONVERSION – ANOTHER WAY
>>> # Example to convert keyboard input data type to integer data type
>>> your_age = int(input('Type your age: ')) #1) convert the input data to integer type
Type your age: 8
>>> sister_age = int(input('Type your sister age: ')) #2)
Type your sister age: 3
>>> age_addition = your_age + sister_age
>>> print(age_addition)
11
>>>

Code line 1):

>>> your_age = int(input(‘Type your age: ‘))

The above statement takes the input from the keyboard and treats it as an integer int type.

Number Type Conversion

In many situations, you need to convert the int data type to the float data type or vice versa.

To convert a float data type x to an integer int data type number, the following statement is used.

>>> int(x)

This statement will convert the float data type number to int data type.

To convert an int data type number y to a float data type, you issue the following statement.

>>>float(y)

The above statement will convert the integer variable y to a floating point number (float data type).

The program below shows the result of this data type conversion.

PROGRAM EXAMPLE: NUMBER TYPE CONVERSION
>>> x = 3.14159
>>> # Convert x to integer
>>> int(x)
3
>>> y=300000000 #Speed of light in meters per second.
>>> # Convert y to float
>>> float(y)
300000000.0
>>>

More Data Type Conversion Examples

The following Python statements show the results of converting several floating-point numbers to integer data types.

>>>print(int(1.3))   # prints 1

>>>print(int(1.7))   # prints 1

>>>print(int(-1.3))  # prints -1

>>>print(int(-1.7))  # prints -1

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Verified by MonsterInsights