In this tutorial, we are covering two data structures in python programming. Python is one of the most popular and widely used programming languages in the world. It is used for data analytics, machine learning, and even design. It is used in a wide range of domains owing to its simple yet powerful nature. Python 3 is a high-level, general-purpose programming language. In this article, we will be discussing python dictionary and list datatypes.
Source: Google Images
Python also has advanced data structures as well, such as stacks or queues, which can be implemented with basic data structures. They are rarely used in data science and more commonly used in the software engineering and implementation of these complex algorithms so we won’t discuss them in this tutorial.
For Beginners, free Python tutorials and libraries like numpy and pandas, you can refer to Introduction to Python.
Learning Objectives
This article was published as a part of the Data Science Blogathon.
Lists are just like arrays. Python lists are mutable data types in Python. A list refers to the collection of index value pair-like arrays in C/C++/Java. Lists is a 0-based index datatype, meaning the index of the first element starts at 0. Lists are used to store multiple items in a single variable. Lists are one of the 4 data types present in Python, i.e., Lists, Dictionaries, Tuples & Sets. A list is created by placing elements in [ ] separated by commas ‘, ‘. We can use them to store more complex data structures other than integers, strings, or floats. A list of dictionaries is a great example.
The elements of lists can be done by placing index numbers in square brackets, as shown below:
Python Code:
Output
Ahmedabad 30
We also have a negative index number, as shown below:
print(city_list[-1])
Output
Coimbatore
A negative index references the list from the last value; in this case, it is Coimbatore.
The index range represents the portion of the list that you want to extract, as shown in the example below:
print(city_list[2:5])
Output
['Ahmedabad', 'Surat', 'Lucknow']
If you want to find the index value of an item in lists provided the item is in the know, this can be done as shown below:
print(city_list.index('Chennai',0,3))
Output
1
The addition of two lists can be performed using the + operator. The + operator concatenates both the lists.
num_city_list= num_list+ city_list print(num_city_list)
Output
[10, 20, 30, 40, 50, 60, 70, 80, 90, 'Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
The * operator is used to extend the list by copying the same values.
new_citylist= city_list*2 print(new_citylist)
Output
['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore', 'Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
A list is nested if another list is present inside it. There are two elements in the below list, and both are listed.
list_nest
Output
[[10, 20, 30], ['a', 'b', 'c']]
The elements of a nested list can be accessed as shown below
print(list_nest[1][2])
Output
c
In updating the list, there is various function. One can append, extend, insert, and change the lists. We will see all of them one by one.
Append is used when you want to add one item to the list.
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore'] city_list.append('Bangalore') print(city_list)
Output
['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore', 'Bangalore']
Extend is used when you want to add more than one item to the list
num_list=[10,20,30,40,50,60,70,80,90] num_list.extend([100,110,120,130,140,150]) print(num_list)
Output
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]
Change is used when you want to update a specific item in a list.
num_list[7]= 200 print(num_list)
Output
[10, 20, 30, 40, 50, 60, 70, 200, 90, 100, 110, 120, 130, 140, 150]
It is used to insert values at the provided index
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore'] city_list.insert(4,'Vadodara') print(city_list)
Output
['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Vadodara', 'Lucknow', 'Coimbatore']
You can remove an item in a list by providing the item index or range that needs to be removed.
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore'] del city_list[4] print(city_list)
Output
['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Coimbatore']
del city_list[4:6] print(city_list)
Output
['Agra', 'Chennai', 'Ahmedabad', 'Surat']
You can also delete the complete list using the below command
del city_list
This is very easy to do, as shown below:
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore'] city_list=[] print(city_list)
Output
[]
Length is used to find how many elements are present inside the list.
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore'] print(len(city_list))
Output
6
Clear is used to delete elements in a list
num_list=[1,2,2,2,3,4,5,6,6,7,6,7] print(num_list.clear())
Output
None
The reverse function is used to reverse the elements of a list, as shown below:
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore'] city_list.reverse() print(city_list)
Output
['Coimbatore', 'Lucknow', 'Surat', 'Ahmedabad', 'Chennai', 'Agra']
Sort is used to sort the elements in a list. By default, it sorts in ascending order. To sort in descending order, one parameter needs to be provided in the sort function, as shown below:
num_list=[1,2,2,2,3,4,5,6,6,7,6,7] num_list.sort(reverse=True) print(num_list)
Output
[7, 7, 6, 6, 6, 5, 4, 3, 2, 2, 2, 1]
Dictionaries are mutable data types,unordered in nature, meaning they can be updated after they are created.key:value pairs, and the keys must be unique. You can get a list of keys by calling a dictionary instance’s keys method. Syntactically they are written in a key, value pair format inside curly braces/curly brackets. We can update and delete the elements of the list of dictionaries. Dictionaries are implemented using hash tables.
{Key1:Value1,Key2:Value2,Key3:Value3,Key4:Value4}
Keys are always unique, and there cannot be any duplicates. There is no index in the dictionary, meaning they are not ordered. The key is the default iterator and is used to retrieve the value.
Source: trytoprogram
There are four ways in which a dictionary can be created.
The syntax for an empty dictionary is :
dict_emp={} print(dict_emp)
Output
{}
dict_city={1: 'Ahmedabad', 2: 'Chennai', 3: 'Coimbatore',4:'Surat',5:'Agra'} print(dict_city)
Output
{1: 'Ahmedabad', 2: 'Chennai', 3: 'Coimbatore', 4: 'Surat', 5: 'Agra'}
dict_travel={'Country1':'USA', 'Country2': 'India', 'Country3':'Japan', 'Country4':'UK', 'Country5': 'Australia'} print(dict_travel)
Output
{'Country1': 'USA', 'Country2': 'India', 'Country3': 'Japan', 'Country4': 'UK', 'Country5': 'Australia'}
mixed_dict= {'Country':'India', 1456:'Free','list':['city', 'road',12]} print(mixed_dict)
Output
{'Country': 'India', 1456: 'Free', 'list': ['city', 'road', 12]}
print(len(dict_salesid))
Output
5
Let’s create two dictionary
dict_salesid= {'SID1': Fiat 'SID2': Mercedes 'SID3': Maruti 'SID4': Volkswagen 'SID5': Kia}
dict_salesinfo= {'SID':Fiat, 'Sales': 20000 'LaunchDay':'Wed' 'Cost': 500000}
To access the value associated with any of them, we will use the following syntax:
sales_id='SID2' if sales_id in dict_salesid: name= dict_salesid[sales_id] print('Sales ID is {}, Sales name is {}'. format(sales_id,name)) else: print('Sales ID {} not found'.format(sales_id))
Output
Sales ID is SID2, Sales name is Mercedes
First, we set the dictionary element and then retrieve it using the get function.
dict_salesinfo['LaunchDay']='Thurs' dict_salesinfo['Cost']=6000000 LaunchDay= dict_salesinfo.get('LaunchDay') Cost=dict_salesinfo.get('Cost') print('Launchday is {}, Cost is {}'. format(LaunchDay,Cost))
Output
Launchday is Thurs, Cost is 6000000
dict_values= dict_salesinfo.values() print(dict_values)
Output
dict_values(['Fiat', 20000, 'Wed', 500000])
The item function converts a dictionary item into a tuple
dict_items= dict_salesinfo.items() print(dict_items) print(type(dict_items))
Output
dict_items([('SID', 'Fiat'), ('Sales', 20000), ('LaunchDay', 'Wed'), ('Cost', 500000)]) <class 'dict_items'>
for key, value in dict_salesinfo.items(): print(key +"-"+str(value))
Output
SID-Fiat Sales-20000 LaunchDay-Wed Cost-500000
A dictionary object contains key-value pairs, and the list must adhere to this format, or else it will throw an error.
sales_infolist=[['SID','Fiat'],['Sales','20000'],['LaunchDay','Wed'],['Cost','500000']] print(type(sales_infolist)) sales_infolist_dict= dict(sales_infolist) print(type(sales_infolist_dict))
Output
<class 'list'> <class 'dict'>
dict_salesinfo_new= dict_salesinfo.copy() print(dict_salesinfo_new)
Output
{'SID': 'Fiat', 'Sales': 20000, 'LaunchDay': 'Wed', 'Cost': 500000}
The update method is used to update the dictionary object with a value
dict_salesinfo= {'SID':'Fiat','Sales': 20000,'LaunchDay':'Wed','Cost': 500000} dict_salesinfo.update({'Profit':'50000'}) print(dict_salesinfo)
Output
{'SID': 'Fiat', 'Sales': 20000, 'LaunchDay': 'Wed', 'Cost': 500000, 'Profit': '50000'}
A dictionary object can be deleted using the del statement
del dict_salesinfo
Output
The dictionary object is deleted
To delete a specific item, pass on the dictionary key in the del statement as shown below:
del dict_salesinfo['SID'] print(dict_salesinfo)
Output
{'Sales': 20000, 'LaunchDay': 'Wed', 'Cost': 500000}
Another way to delete a specific item is by using the pop function.
print(dict_salesinfo.pop('SID'))
Output
Fiat
The pop function also returns the key value that is being deleted. In this case, it is Fiat.
The third method to delete a dictionary object is using the clear method.
print(dict_salesinfo.clear())
Output
None
We will use the same dictionary object dict_salesinfo. Using the keys function, first, save all the keys in a dict_key variable
dict_keys= dict_salesinfo.keys()
print(dict_keys)
print(type(dict_keys))
Output
dict_keys(['SID', 'Sales', 'LaunchDay', 'Cost']) <class 'dict_keys'>
for var in dict_keys:
print(var + “:” + str(dict_salesinfo[var]))
Output
SID:Fiat Sales:20000 LaunchDay:Wed Cost:500000
In Python, a list is a class of data structures that can store one or more objects or values. A list can store multiple items in one variable and be created using square brackets. Dictionaries are used to store data values in key:value pairs. A dictionary is an ordered, changeable collection, and does not allow duplicates. Elements of the dictionary are accessed through the keys.
Key Takeaways
A. The main difference is we can access items in a python dictionary and dictionary values via keys and not by their position. A list is an ordered sequence of objects, whereas dictionaries are unordered sets.
A. We can use a list and a dictionary depending on the problem statement. Lists are used to store data in an ordered and sequential pattern. In comparison, a dictionary is used to store large amounts of data for easy and quick access. A list is ordered and mutable, whereas dictionaries are unordered and mutable.
A. We can store data in multiple ways, like Lists, Tuples, and dictionaries.
Lorem ipsum dolor sit amet, consectetur adipiscing elit,