Data Structures in python are one of the important aspects in Data Science. By definition, Data Structures are different ways to store data in a system.

Both data structures and algorithms are related to each other i.e., one cannot exists without the other. A data structure provides an efficient storage format for our data which ensures easy access, and modification. It collects data, and defines the relationship among them and describes the operations to be done on the data.

Python has many data structures which simplify the life of a Data Scientist in solving complex problems instead of worrying about the description of data and its accessibility. 

Data structures can be categorized into Primitive and non-Primitive data structures. Primitive data structures represent data in a simple form, whereas non-primitive data structure is more advanced, and complicated in nature.

The Primitive Data structure in Python are of the following types:

  • Integers – It represents whole numbers such as 1, 2, 3, etc.
  • Float – The floating-point numbers end with decimal values such as 10.5, 11.8.
  • Strings – It represents words, alphabets, etc. In Python, strings are written inside single or double-quotes. E.g.:- “Python”.
  • Boolean – Booleans are used in conditions and it’s represented by True, and False.

The non-Primitive Data structure in Python are the following:

  • List – Lists are mutable and it could store different types of data. It is written within square brackets where each element is separated from another with a comma. E.g.: [1, ‘One’, 2, ‘Two’] is a list.
  • Tuple – Unlike lists, tuples are immutable in nature. Tuples are written within the opening and closing parenthesis. E.g. (1, ‘One’, 2, ‘Two’) is a tuple.
  • Set – In a set, the data is unordered, mutable, and it consists of only unique elements. Sets works on the principle of the hash table which makes it extremely efficient in terms of finding an element as compared to a list.
  • Dictionary – A dictionary is a key-value pair data type which consists of unordered data and is represented within curly {} brackets. E.g.: {1: ’One’, 2: ’Two’} is a dictionary.

So far we have got a brief idea about Data Structures in Python and their usefulness in the real world. In this article, we would look into the Dictionary data type in detail along with some examples.

What is a Python Dictionary?

Dictionaries are the ordered data types consisting of key-value pairs. The keys are unique, and immutable whereas the value of a particular key could be changed. The keys could be of any type and all the keys are separated with a comma while all the key-value pairs are separated with ‘:’.

Dictionaries are case-sensitive i.e., keys with capital and small letters would be treated differently.

Creating a Python Dictionary

An empty dictionary could be created using the {}

#Creating an Empty Dictionary
d = {}
print(d)

{}

Creating a dictionary having integers as keys

d = {1; 'One', 2; 'Two', 3; 'Three'}
print(d)

{1; ‘One’, 2; ‘Two’, 3; ‘Three’}

 

Creating a dictionary having mixed values as keys

d = {'Name': 'TechLearn', 1: [1,2,3,4]}
print(d)

{‘Name’: ‘TechLearn’, 1: [1,2,3,4]}

 

Creating a dictionary using the dict () method

d = dict({1: 'One', 2: 'Two', 3: 'Three'})
print(d)

{1: ‘One’, 2: ‘Two’, 3:’Three’}

 

Taking each item as a pair to create a dictionary using the dict () method

d = dict([(1, 'One'), (2, 'Two')])
print(d)

{1: ‘One’, 2: ‘Two’}

 

A Nested Python Dictionary is a dictionary within a dictionary.

Creating a nested dictionary in python

d = {1: 'One', 2: 'Two',
3: {'A': 'Welcome', 'B': 'To', 'C': 'TechLearn'}}

{1: ‘One’, 2: ‘Two’, 3: {‘A’: ‘Welcome’, ‘B’: ‘To’, ‘C’: ‘TechLearn’}}

 

Manipulating a Python Dictionary

Several operations like additions, deletion, etc. could be performed on the dictionary.

Adding elements in a dictionary

In this example, values are added one after the other in an empty dictionary

d = {}
d[0] = 'Zero'
d[2] = 'Two'
d[3] = 1

print(d)

{0: ‘Zero’, 2: ‘Two’, 3: 1}

 

Adding multiple values in a dictionary with a single key

d['multiple_value'] = 2, 3, 4
print(d)

{0: ‘Zero’, 2: ‘Two’, 3: 1, ‘multiple_value’: (2, 3, 4)}

 

To update the current value of a key

d[2] = 'Dictionary'
print(d)

{0: ‘Zero’, 2: ‘Dictionary’, 3: 1, ‘multiple_value’: (2, 3, 4)}

 

In a Dictionary, we could also add nested key-value pair to any key

d[5] = {'Nested':{'1': 'One', '2': 'Two'}}
print(d)

{0: ‘Zero’, 2: ‘Dictionary’, 3: 1, ‘multiple_value’: (2, 3, 4), 5:{‘Nested’: {‘1’: ‘One’, ‘2’: ‘Two’}}}

 

Fetching data in a Dictionary

Creating a new dictionary and fetching an element based on the key

d = {1: 'One', 'name': 'TechLearn', 3: 'Three'}

#Printing the element with key as name
print(d['name'])

TechLearn

 

Accessing the element with a different key

d = {1: 'One', 'name': 'TechLearn', 3: 'Three'}

#Printing the element with key as 3
print(d[3])

Three

 

Using the get () method to access elements in a dictionary

d = {1: 'One', 'name': 'TechLearn', 3: 'Three'}

#Printing the element with key as 1 using the get() method
print(d.get(1))

One

 

Deleting elements in a Dictionary in Python is so easy

Like addition, elements of a dictionary could also be removed either by using the del keyword or by using functions like pop () and popitem (). To delete specific values from a dictionary or to remove the entire dictionary, the del keyword is used, whereas to remove arbitrary values pop () and popitem () functions are used. To remove the entire dictionary at one go, clear() function could be used. To deleted nested elements, the appropriate keys should be mentioned in the del keyword.

Creating a new dictionary and removing the value with a key as 6

d = {s: 'Welcome', 6: 'To', 7: 'TechLearn'
'A': {1: 'One', 2: 'Two', 3: 'Three'},
'B': {1: 'One', 2: 'Two'}}

#Deleting the element with key as 6
del d[6]
print(d)

{5: ‘Welcome’, 7:’TechLearn’, ‘A’: {1: ‘One’, 2: ‘Two’, 3: ‘Three’}, ‘B’: {1: ‘One’, 2: ‘Two’}}

 

Deleting the value with nested keys as ‘A’ and 2

del d['A'][2]
print(d)

(s: ‘Welcome’, 7: ‘TechLearn’, ‘A’: {1: ‘One’, 3: ‘Three’}, ‘B’:{1: ‘One’, 2: ‘Two’})

 

Using a pop() command to delete a key

d.pop(5)
print(d)

{7: ‘TechLearn’, ‘A’: {1: ‘One’, 3: ‘Three’}, ‘B’: {1: ‘One’, 2: ‘Two’}}

 

Deleting the last element using the popitem() command

d.popitem()
print(d)

{7: ‘TechLearn’, ‘A’: {1: ‘One’, 3: ‘Three’}}

 

Deleting the entire dictionary at once using the clear() command

d.clear()
print(d)

{}

 

Additional functions in Dictionary

Apart from those methods already discussed, there are few additional functionalities or methods used in the Dictionary.

keys() – Used to get all the keys in a dictionary

d = {1: 'One', 2: 'Two', 3: 'Three'}
print(d.keys())

dict_keys{[1, 2, 3]}

 

values() – to get all the values in a dictionary

print(d.values())

dict_values([‘One’, ‘Two’, ‘Three’])

 

items() – Used to get all the key-value pairs in the form of a tuple

print(d.items())

dict_items([(1, ‘One’), (2, ‘Two’), (3, ‘Three’)])

 

update() – Updates one dictionary with the key-value pairs of another

d1 = {'A': 'For', 'B': 'TechLearn'}
d2 = {'B': 'Two'}

d1.update(d2)
print(d1)

{‘A’: ‘For’, ‘B’: ‘Two’}

 

Conclusion

Dictionaries are one of the most important Data Structures to master for any Data Scientist. There are plenty of resources to learn dictionaries online.

TechLearn Blog consists of several handy articles on Python Dictionaries.

The official website of Python could also be referred to learn Dictionaries.

LEAVE A REPLY

Please enter your comment!
Please enter your name here