Python Tuple & Dictionary

Machine Learning & Data science course

Are you interested in machine learning, data science, AWS, R programming, python, rstudio, jupyter notebook, pandas, numpy, etc?

If you answered yes to any of the above, click on the button to enroll in one of the most comprehensive & affordable machine learning course. 

What our students are saying about Machine learning course

This course is a great introduction to data science. Best part I got this in a deal for only 4000 rupees. A big tour through a lot of algorithms making the student more familiar with machine learning. Theory explanation provide good background in clearing concepts, though I think it could be further improved but nonetheless, it is a very good course because it covers every aspect of machine learning with R.

Shilpi

Great course to introduce to machine learning concepts, statistics and visualization with hands-on examples. This course is very practical and helped me to start my machine learning journey. I know I still need to go long way but at this price point, it’s a great course.

Shaurya

In last post, we covered basic data types in python. In this post, we are going to cover few advance and important data types in python;

  • Tuples
  • Dictionaries

If you are not clear about;

  • Numbers
  • Strings
  • Boolean
  • Python list

Please click here & go through last post on them.

If you are yet to install python or need information on python comments or variables, click on the appropriate link below;

  1. How to install python & anaconda distribution
  2. Python comments & variables

You will find sample code file at the bottom of the post.

Python Data Types

Python Tuple

Python tuples are python objects with close resemblance to python lists. In fact, a lot of time people tend to get confused between tuples and lists.

Just as we saw that python list can be used to store multiple values, tuples can also be used to store multiple values in them.

Tuple in python are created with parenthesis ().

They will always have a trailing comma if they only have 1 value.

They are immutable, so you cannot update them.

They are used when you need object which is constant.

Tuple cannot be updated but they can be accessed, sliced or concatenated just like most other python objects.

You can create an empty tuple with following syntax;

firsttuple = ()

This is an empty tuple.

Quick Note

If you are supplying it values, you need to ensure that you add a trailing comma even if there is only one value. Because if you don’t add a comma after value, python will treat as a string or integer/floating instead of a tuple.

Let’s look at these examples;

python tuple

You can store numbers and strings together in a tuple.

As I have mentioned earlier, you cannot update a tuple, but you can still perform other operations on them like you can take multiple tuples and join them to create a new tuple.

python tuple 2

As I have mentioned earlier, there is lot of confusion between list and tuple so maybe this table will help you out with the difference between them;

List

Tuple

Python lists are mutable which is, they can be updated.

Python tuple are immutable which is, they cannot be updated

They are usually created with square brackets [].

Tuple are usually created with parenthesis ().

There is no trailing comma in list with only 1 value.

Tuple containing only 1 value need to have a trailing comma otherwise python will treat object as any other variable like string, integer etc.

List of same size will usually consume more memory and will be slower than tuple.

Tuple of same size will usually consume lesser memory than list and will be faster than the list of same size.

This is a very high-level overview of Tuple, but I have highlighted all the important points. Their index starts from 0 so to access a particular value, you can use following syntax;

Tuple[indexnumber]

I have performed few more operations which can find in this screenshot.

python tuple 3

You can explore it more and leave your comments if you have any doubt.

Python Dictionary

Python dictionary is like associative array in few other languages. It is created with curly brackets and contains data in the format of “key”:”value” pair.

Python dictionaries are un-ordered, and their values can be updated (mutable).

Please note that keys are unique within a dictionary. For example, let’s create a small dictionary with 2 values;

first_dic = {

    "Key1": "Ford",

    "Key2": "Mahindra"

}

In this example, Key1 and Key2 are unique values and they cannot be repeated.

As we have seen earlier with lists, we were using index/position to access a value but that cannot be dine with dictionary.

Values in dictionary are accessed via key value. So, in the above example, we can use Key1 and Key2 to access corresponding values.

Adding values to a dictionary is quite simple, you select the dictionary[“keyname”] and pass the value of key;

Dictionary[“key”] = “value”

Please note if they key already exist in the dictionary, it will be updated with the value whereas if the supplied key value doesn’t exist in the dictionary, it will create a new key value pair in the dictionary.

We have created a dictionary with two keys-Key1 and Key2.

Let’s try to update this one;

first_dic["Key3"] = "BMW"

now if we print first_dic dictionary,

Out[23]:

{'Key1': 'Ford', 'Key2': 'Mahindra', 'Key3': 'BMW'}

Now if run same command with existing key like Key1. It will update its value instead of creating a new one.

first_dic["Key1"] = "JLR"

now print it;

Out[25]:

{'Key1': 'JLR', 'Key2': 'Mahindra', 'Key3': 'BMW'}

Key1 has been updated to JLR from Ford.

Now let’s create a nested dictionary which simply means dictionary within a dictionary.

#nested dictionary

sec_dic = {

    "Name": "Akhilendra",

    " Age": 36,

    "Address": {

        "City": "Noida",

        "State": "Uttar pradesh"

    }

}


python dictionary 1
python dictionary 2

We can use item method to loop through a dictionary and print its key: values like;

for a, b in sec_dic.items():

...     print(a, b)

It will produce following output;

Name Akhilendra

 Age 36

Address {'City': 'Noida', 'State': 'Uttar pradesh'}

We can use pop() function to remove a value from the dictionary;

sec_dic.pop(" Age")

output will be;

{'Name': 'Akhilendra', 'Address': {'City': 'Noida', 'State': 'Uttar pradesh'}}

python dictionary 3

Few other commonly used python methods which are used with python dictionaries.

Method

Description

clear()

Remove all items form the dictionary.

copy()

Return a shallow copy of the dictionary.

get(key[,d])

Return the value of key. If key doesnot exit, return d (defaults to None).

keys()

Return a new view of the dictionary's keys.


If you have any doubt or feedback, please leave your comment.

Download Jupyter notebook with code

About akhilendra

Hi, I’m Akhilendra and I write about Business Analysis, Data Science, IT & Web. Join me on Twitter, Facebook & Google+

Speak Your Mind

*