Python Data Structures Conversions (List , Set & Dictionary) | by Kieran Tan Kah Wang | Towards Data Science

In Python, there is primarily two data types mainly Atomic and Collective. Atomic data types are indivisible which represents only a single data value. Some examples are integer (int), floating point (float) and boolean (bool). Collective data types on the other hand are a collections of multiple data values which consists of string (str), list (list), tuple (tuple), set (set) and dictionary (dict). This article will focus on list, set and dictionary, and ways to convert between them without any inbuilt python commands.
Python list is a data type for a collection items which are generally related and they can hold data objects of any data type (i.e. string, int, bool) as shown below. They are usually captured using square brackets (i.e. [ ])
a_list = [1, 'two', 3.0, '4']
Some common useful list commands are as follow. Note that indexing in Python starts at 0 instead of 1 in other programming languages like R.
# define empty lista_list = []# append new item into list at the end of the lista_list.append(new_item)# append new item into list at a specific indexa_list.insert(index, new_item)# remove an item from the list based on indexa_list.pop(0)# remove an item from the list based on item valuea_list.remove('two')# sort the items in ascending order, note that the data types must be similara_list.sort()# reverse the order of the itemsa_list.reverse()
A set is a data type for representing a collection of unique, unordered items. They are usually captured in a curly brackets (i.e. { }). Due to the fact that a set is unique and unordered, there’s no way in Python which we can access individual items based on indexing or item assignment. Some common useful set commands are as follow:
# define an empty seta_set = set()# define a seta_set = {'one', 2}# adding item to a seta_set.add('c')# removing an item from a set, raise keyError if item does not exista_set.remove('one')# removing an item from a set, no keyError if item does not exista_set.discard('one')# remove the first item from a set and return ita_set.pop()# remove all items from a seta_set.clear()
A dictionary is a mapping data type that associates a key with a value, which somewhat explains what a dictionary is (i.e. looking up a word and it has a meaning provided). Each data item is represented as key : value. Note that key values must be immutable types meaning they should be unchanged, while data values can be of any data types. Some common useful dictionary commands are as follow:
# define an empty dictionarya_dict = {}# define a dictionarya_dict = {"one":1, "two":2}# adding new items to the dictionarya_dict[new_key] = new_value# removing items from the dictionarydel a_dict[a_key]# display the keys in the dictionarya_dict.keys()# display the values in the dictionarya_dict.values()# display the items in the dictionarya_dict.items()
We can easily use the set[a_list] to convert a list into a set. However, I personally feel that the best way to know how data structure works is to try creating them from scratch. The function below will first define an empty set and then using for loop which will loop through each value in a given list, it will add it into a set. Bearing in mind that a set is an unique data structure, even if there are duplicated values in the given list, it will not be added to the set.
def list_to_set(int_list):    my_set = set()    for each in int_list:        my_set.add(each)        return my_set
Remember a dictionary is a key-value pair which is why if we were to create a dictionary from scratch, we will need two separate lists, one for keys and the other for values. This function will first create an empty dictionary and then using a for loop with the range option, it will loop through each element in both list and tag it as a key-value pair. Bear in mind that the order in this two lists matter as we are going to tag a key to a value in the value list based on position indexing. Also, the length of both lists must be similar.
def list_to_dict(key_list, value_list):    my_dict = {}    for i in range (0, len(key_list)):        my_dict[key_list[i]] = value_list[i]            return my_dict
For this portion, we will introduce a new data type called the tuple which was not introduced earlier. A tuple is multiple data items in a bracket (i.e. ( )) and a tuple set is simply a set of multiple unique tuples. An example of tuple with two items is (1, 2) while a tuple set can be {(1,2) , (1,3)}. With tuples of two data items, it seems to suggest we can build a dictionary out of a tuple set.
As usual, we first define an empty dictionary. Then, we will use a for loop to loop through each tuple. Since there are two data items in each tuple, the first value will be our dictionary key, while the second will be our it’s value.
def set_to_dict(tuple_set):    my_dict = {}    for each in tuple_set:        my_dict[each[0]] = each[1]        return my_dict
In this article, we have introduced the three most common collective data types in Python (i.e. List, Set, Dictionary) and some common useful Python commands. Data conversions were then discussed in details on converting between them from scratch without using inbuilt Python commands. I hope this article can give Python-enthusiasts a head start in being familiar with Python data structures and decide which data structure is the most suitable on different problems/business needs, cheers!