Open In Colab

Python Dictionary from Scratch!!!

Let us understand the fundamentals of dictionaries in python.

alt text

Dictionary in python comprises an unordered collection of data stored in a key: value format. Dictionary is also known as "Associative memories" or "Associative arrays". In a dictionary, the key must always be unique. Whereas the values can be repeated and can be of any data type. The key-value pair should be represented as "key: value" (: colon is a must). Shown below are some most used dictionary methods and are one of the most commonly asked interview questions.

For example, declaring a dictionary in python:

In [85]:
# Declaring a dictionary

dictionary = {}
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23}
In [86]:
print(type(dictionary))
<class 'dict'>

1) Accessing the elements in a dictionary

Dictionaries can be accessed by their index to get the value. To do this, all you have to do is just place the number or the name of the key inside the pair of square brackets along with the name of the dictionary.

In [87]:
# Accessing the elements in a dictionary

dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23}
In [88]:
print(dictionary['Name'])
Tanu
In [89]:
print(dictionary['Sex'])
Male

If you try to access the key which is not declared in the dictionary then an exception would be raised indicating no results found:

In [42]:
dictionary['Height']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-42-038ad6c9b2d4> in <module>()
----> 1 dictionary['Height']

KeyError: 'Height'

Also, we can use the get() of the dictionary to get or access the values of the dictionary as seen below:

In [90]:
print(dictionary.get('Age'))
23

2) Removing the elements from a dictionary.

In python, there are four different ways or methods that can be used to remove an element from a dictionary. Those are pop, del, popitem and clear. The del is used to delete a key from a dictionary, the pop is used to remove a specific key from a dictionary, popitem is used to remove the key arbitrarily from a dictionary, and the clear is used to just clear or delete all the elements in the dictionary (as the name suggests).

In [55]:
# Removing the elements from a dictionary

dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
In [56]:
# Deleting an element

del dictionary['Name']
print(dictionary)
{'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
In [57]:
# Popping an item

print(dictionary.popitem())
('Occupation', 'Student')
In [58]:
# Popping the value

print(dictionary.pop('Sex'))
Male
In [59]:
print(dictionary)
{'Age': 23, 'Height': 5.8}
In [60]:
# Clearing the entire dictionary

dictionary.clear()
print(dictionary)
{}

3) Iterating Through a Dictionary

Using a for loop we can iterate through each key in a dictionary as shown below:

In [91]:
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
In [62]:
# Iterating through the values

for i in dictionary:
    print(dictionary[i])
Tanu
Male
23
5.8
Student
In [63]:
# Iterating through the keys

for i in dictionary:
    print(i)
Name
Sex
Age
Height
Occupation

4) All

The all () in dictionary returns "True" if all keys of the dictionary are true (or if the dictionary is empty). If the keys in the dictionary are true or if the dictionary all method returns true or else it will return false.

In [64]:
dictionary = {0: "Tanu", 1: "Prabhu"}
print(dictionary)
{0: 'Tanu', 1: 'Prabhu'}
In [65]:
print(all(dictionary))
False
In [66]:
dictionary = {1: "Tanu", 1: "Prabhu"}
print(all(dictionary))
True
In [67]:
dictionary = {}
print(all(dictionary))
True

5) Any

The any () in dictionary return "True" if any key of the dictionary is true. If the dictionary is empty, returns "False".

In [68]:
dictionary = {0: "Tanu", 1: "Prabhu"}
print(dictionary)
{0: 'Tanu', 1: 'Prabhu'}
In [69]:
print(any(dictionary))
True
In [70]:
dictionary = {0: "Tanu", 0: "Prabhu"}
print(any(dictionary))
False
In [71]:
# 0 is False

dictionary = {0: "Tanu"}
print(any(dictionary))
False

6) Len

The length () method in the dictionary returns the length of the dictionary (obviously). It returns the number of items of the dictionary.

In [92]:
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
In [73]:
print(len(dictionary))
5

7) Sorted

The Sorted() method in dictionary returns a new sorted list of keys in the dictionary.

In [74]:
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
In [75]:
# Sorting in a ascending order

print(sorted(dictionary))
['Age', 'Height', 'Name', 'Occupation', 'Sex']
In [76]:
# Sorting in a descending order

print(sorted(dictionary, reverse = True))
['Sex', 'Occupation', 'Name', 'Height', 'Age']

The sorted() method accepts a reverse parameter as an optional argument.


8) Copy

As the name suggests the copy method in dictionary returns a copy of the dictionary.

In [77]:
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
In [78]:
dictionary1 = {}
print(dictionary1)
{}
In [80]:
dictionary1 = dictionary.copy()
print(dictionary1)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}

9) Keys

Python dictionary method key() returns a list of all the available keys in the dictionary.

In [81]:
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
In [93]:
print(dictionary.keys())
dict_keys(['Name', 'Sex', 'Age', 'Height', 'Occupation'])

10) Values

Python dictionary method values() returns a list of all the values available in a given dictionary.

In [83]:
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
In [84]:
print(dictionary.values())
dict_values(['Tanu', 'Male', 23, 5.8, 'Student'])

Hence above are the very important techniques or functions of Dictionary in Python. Some of the examples were referred from Python Dictionary. I have written this tutorial in a simple way such that everybody can understand and master the concepts of Dictionaries in Python without prior programming knowledge or experience. If you guys have some doubts in the code, the comment section is all yours. Thank you have a good day.