Python Dictionary

Python Dictionary

Python dictionary had gained a lot of popularity, especially, since the last decade. It has tremendously impacted the modern programming aspect. Mostly all the new technologies that are supported and implemented using Python uses dictionaries, such as Machine Learning, Data Science, Big Data, Deep Learning, AI and many others. After learning ListTuple and Sets in our previous section, in this single tutorial, you will gain complete knowledge to work efficiently with Python dictionaries.

Table of contents

  1. What is a Python dictionary
  2. Why use python dictionary
  3. How to create Python dictionary
  4. How to access dictionary elements
  5. How to add items to dictionary
  6. Remove key and value from the dictionary
  7. Python dictionary methods
  8. To delete the dictionary in Python
  9. Conclusion

Introduction to Python dictionary

Python Dictionary is a paired collection of unordered elements, group together under one name. Dictionary can hold elements of multiple data types(Heterogenous) and elements are accessed via key indexing. You got three characteristics about python dict, which are, Paired, Unordered and Key Indexing.

In the real-world scenario, we all have seen dictionary (mostly language dictionary) that relate word from one language to other. The similar requirement arises in the programming language as well, to connect a keyword with alike ones. Image shown below represents the pictorial comparison between Language and Python dictionary.

Python dictionary vs language dictionary

Need for python dictionary

Dictionary provides a provision to store key-value pair elements under one name. Key-Value pair is required in many circumstances such as storing month name with month number, name of persons along with corresponding ages, column name with all column value and many more. These pair can’t be stored in any other data structures provided by Python programming language.

Pandas, a modern data handling and manipulation library, also incorporate dictionary features to store and access elements. As you progress through this tutorial, you will get to know more about Python dictionaries in details.

How to create Python dictionary

Dictionary can be created in three different ways.

Three Method

i) Using curly braces

dict1 = { }  # to create an empty dictionary
print (dict1)
{ } # returns an empty dictionary

Interesting fact: Creating an empty set or empty dictionary, uses the same syntax but if you check the data type of an empty set or dictionary. It will show <class ‘dict’> as shown below

d1 = { } # for empty dictioonary
s1 = { } # for empty set
type(d1)
<class 'dict'>

type (s1)
<class 'dict'>

Set and Dictionary starts getting differentiated after the elements are getting placed inside the curly braces. If the elements are simply separated by comma (, ) then it takes the class as ‘set’ otherwise if elements pair, with ” : ” (colon) in between, are separated by a comma then it takes the class as ‘dict’.

set2 = { elem1, elem2, elem3 } # create set with some elements
type (set2)
<class 'set'>

Tips: Don’t forget to put strings under single or double quotes.

dict2 = { 'jan' : 1 , 'feb' : 2 } #create dictionary with key-value pair
type(dict2)

ii) Using dict () method

Dictionary can also be created using python dict method as shown below

dict2 = dict ( )
dict3 = dict ( {'jan' : 1 , 'feb' : 2 } )
print (dict3)
{'jan': 1, 'feb': 2}

iii) Using Tuple inside a list method

Dictionary can also be created by placing tuple inside a list. Each tuple contains a key-value pair as shown below.

dict4 = dict ([ ('jan' , 1 ) , ('feb', 2) ])
print (dict4)
{'jan': 1, 'feb': 2}

However, this method is not so popular for creating dictionaries in Python.

Accessing dictionary elements

As you know, a dictionary consists of one or more key-value pairs. There are built-in methods to get the individual element from a dictionary.

Multiple keys and multiple values in the dictionary

Consider a dictionary with the name “share” with the values shown below.

share = {‘name’ : ’IRCTC’, (’cmp’, 'max') : 900, ‘sector’ : [‘Tourist’, ’Hotel’, ’Ticket’] }

As you would notice that for ‘sector’ key, there are more than one values (‘Tourist’, ’Hotel’, ’Ticket’). YES, it is possible to have multiple values for a particular key. These values are mutable (can be changed) thus a list data structure can be used. 

On the other hand, it is also possible to have multiple keys for one value.

share = {‘name’ : ’IRCTC’, (’cmp’, 'max') : 900, ‘sector’ : [‘Tourist’, ’Hotel’, ’Ticket’] }

In this case, the second key-value pair has two key (‘cmp’,’max’) for a single value (900). Keys in a dictionary are non-mutable, so a tuple data structure can be used.

Underline guidelines: A non-mutable data type (like a tuple) can be used as key and a mutable data type (like a list) can be used as the value in the dictionary.

Python dictionary – keys() method

A keys () method in is used to get all the keys of a dictionary. Let’s understand it via an example.

Consider a dictionary with the name “share” with the element shown below. 

share = {'name' : 'IRCTC', ('cmp', 'max') : 900, 'sector' : ['Tourist', 'Hotel', 'Ticket'] }
print ( share.keys() )
dict_keys(['name', ('cmp', 'max'), 'sector'])

Python dictionary values() method

A values () method in is used to get all the values of a dictionary. Let’s understand it via an example.

Consider a dictionary with the name “share” with the element shown below. 

share = {'name' : 'IRCTC', ('cmp', 'max') : 900, 'sector' : ['Tourist', 'Hotel', 'Ticket'] }
share.values()
dict_values(['IRCTC', 900, ['Tourist', 'Hotel', 'Ticket']])

Python dictionary items() method

A items () method in is used to get all the key-values pair of a dictionary. Let’s understand it via an example.

Consider a dictionary with the name “share” with the element shown below. 

share = {'name' : 'IRCTC', ('cmp', 'max') : 900, 'sector' : ['Tourist', 'Hotel', 'Ticket'] }
share.items()
dict_items([('name', 'IRCTC'), (('cmp', 'max'), 900), ('sector', ['Tourist', 'Hotel', 'Ticket'])])

Add items to dictionary

A new item (key-value pair) can be added as well as the existing value can be modified to a dictionary.

Add a new key-value pair to Python dictionary

A new key-value pair can be added using the following method. If the key is already present in the dictionary then the corresponding value will be updated otherwise a new key-value pair will be inserted. 

Let’s see via an example,

share = {‘name’ : ’IRCTC’, ’cmp’ : 900, ‘sector’ : [‘Tourist’, ’Hotel’, ’Ticket’] }
share [‘average’] = 850  # there is no average key in the dictionary
print (share)
{‘name’ : ’IRCTC’, ’cmp’ : 900, ‘sector’ : [‘Tourist’, ’Hotel’, ’Ticket’], ‘average’ : 850 } # it is added to the dictionary.

Modifying existing value in a dictionary

As you have learned if the key is already present in the dictionary then using the following expression we can update the existing value of that particular key. Let’s see via an example.

{‘name’ : ’IRCTC’, ’cmp’ : 900, ‘sector’ : [‘Tourist’, ’Hotel’, ’Ticket’], ‘average’ : 850 }
share [‘cmp’] = 930 # cmp key is available in the dictionary
print (share)
{‘name’ : ’IRCTC’, ’cmp’ : 930, ‘sector’ : [‘Tourist’, ’Hotel’, ’Ticket’], ‘average’ : 850 } # the value of cmp is updated to 930.

Updating a value can also be done using the update () method in python.

*Note– Any datatype can be added/updated to Dictionary Keys and (or) value can be a list

Removing key and value from the dictionary

There are predominantly three-way to remove an element (key-value pair) from a dictionary, which are 

i) pop () method

ii) popitem () method

iii) using del keyword

Python dictionary pop ( ) method

The pop() method removes an element from the dictionary based on the key provided and also returns the value of that key.

dict_name.pop( key [, default] )
num = { ‘one’: 1, ‘two’: 2, ‘three’: 3, ‘zero’:0 }
element = num.pop(‘zero’)
print (element) 
0

Print (num)
{‘one’: 1, ‘two’: 2, ‘three’: 3}

Python dictionary popitem ( ) method

The popitem () method removes any random element (key-value pair) from the dictionary and returns it as a tuple. It is an uncontrolled way of removing an element from a dictionary since we don’t have control to select a particular element for removal.

dict_name.popitem()
num = { ‘one’: 1, ‘two’: 2, ‘three’: 3, ‘zero’:0 }
element = num.popitem()
print (element)
(‘three’, 3)

Print (num)
{‘one’: 1, ‘two’: 2, ‘three’: 3}

Remove a key from dictionary using del

The third way to remove a key from the dictionary is using del. This method supports the deletion of only one key at a time. If you put more than one key in the square bracket, it will throw an error. Let’s look at the example below.

del dictionary_name [ key ]
num = { ‘one’: 1, ‘two’: 2, ‘three’: 3, ‘zero’:0 }
del num['three']

print(num)
{ ‘one’: 1, ‘two’: 2, ‘zero’:0 }

Python Dictionary method

There are several methods associated with Python dictionary. You can find each one of them with detailed examples in this section.

Python dictionary get () method

A get () method in dictionary is used to get the value of a particular key. If the key is not present then we can pass additional (it is optional) argument. In the below-mentioned example, ‘amp’ key is not present in the dictionary. If you try to execute the following expression, it will result in an error.

share = {'name' : 'IRCTC’, 'cmp' : 900, 'sector' : ['Tourist', 'Hotel', 'Ticket'] }
share['amp']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'amp'
dict_name.get ( key, "Optional message or value")

When key is not present

share = {'name' : 'IRCTC’, 'cmp' : 900, 'sector' : ['Tourist', 'Hotel', 'Ticket'] }
share.get (‘amp’, “No such key”) # here we have pased additional argument "No such Key", since key 'amp' is not present in the dictionary
>> No such key

When key is present

share = {'name' : 'IRCTC’, 'cmp' : 900, 'sector' : ['Tourist', 'Hotel', 'Ticket'] }
share.get (‘cmp’, “No such key”) # key 'cmp' is present and we got the result
>> 900

Python dictionary update () method

The update ( ) method in helps to update the value of one or multiple keys (or key-value pair). Update method works in two scenarios described below.

Update the value if key is present

In this case, the update method looks for the presence of all the keys and update it with new value.

number = {1 : ’one’, 2: ‘three’ }
number.update({2:‘two’})
print (number)
{1 : ’one’, 2: ‘two’ }

Add key value pair if key is not present in Dictionary

In this case, the update method looks for the presence of all the keys. This method will update the value all key which already exist as well it will add the new key-value pair if the key is not present in the dictionary.

number = {1 : ’one’, 2: ‘three’ }
number.update({ 2 : 'two', 3 : ‘three’ , 4 : ‘four’ })
print (number)
{1 : ’one’, 2: ‘two’ ,3 : ‘three’ ,4 : ‘four’ }

Python dictionary fromkeys method

A fromkeys() method returns a new dictionary with provided keys and also assignes values for each key (if the value is provided)

dict.fromkeys(sequence [, value] )

Let say a set, with name data, contains five values. If you want to generate a dictionary using these elements as a key then you can generate the dictionary using fromkeys method. This generated dictionary will not have any value for all keys, as shown below.

data = {'a', 'e', 'i', 'o', 'u' }
vowels = dict.fromkeys(data)
print(vowels)
{'a': None, 'u': None, 'o': None, 'e': None, 'i': None}

As you know, only a hashable object can be used as keys for the dictionary, so you should use only set or tuple.

In case, you want to assign each key with the same value, then you could do so in the following way.

data = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel’
vowels = dict.fromkeys(data, value)
print(vowels)
{'a': 'vowel', 'u': 'vowel', 'o': 'vowel', 'e': 'vowel', 'i': 'vowel’}

In case, you want to assign each key with multiple values, then you could do so in the following way.

data = {'a', 'e', 'i', 'o', 'u' }
value = [2, 3]
vowels = dict.fromkeys(data, value)
print(vowels)
{ 'a': [2, 3], 'u': [2, 3], 'o': [2, 3], 'e': [2, 3], 'i': [2, 3] }

Python dictionary setdefault ( ) method

The setdefault() method returns the value of a key if the key is present in the dictionary. If the key is not present, we can choose to set a default value for that key. In the absence of default value, it would return None.

dict_name.setdefault(key[, default_value])

In this example, the key “AI” is present. The setdefault method will output the actual value (which is 1, in this case).

tech = { ‘AI’: 1, ‘DL’: 2, ‘ML’: 3, ‘RL’:0 }
demand = tech.setdefault ( ‘AI’ )
print (demand)
1

In this example, the key “DS” is NOT present. The setdefault method will output a None value as well as it will also insert the new key-value pair in the dictionary, as shown below.

tech = { ‘AI’: 1, ‘DL’: 2, ‘ML’: 3, ‘RL’:0 }
demand_2 = tech.setdefault ( ‘DS’ )
print (demand_2)
None

print (tech)
{ ‘AI’: 1, ‘DL’: 2, ‘ML’: 3, ‘RL’:0, ‘DS’: None }

In this example, the key “DS” is present. The setdefault method should output None value BUT since the number 4 is passed with the setdefault method, so it will return 4 as the output. Additionally, the new value will be assigned to the key in the dictionary, as shown below.

tech = { ‘AI’: 1, ‘DL’: 2, ‘ML’: 3, ‘RL’:0, ‘DS’: None }
demand_3 = tech.setdefault ( ‘DS' , 4)
print (demand_3)
4

print (tech)
{ ‘AI’: 1, ‘DL’: 2, ‘ML’: 3, ‘RL’:0, ‘DS’: 4 }

Python dictionary len() method

The len () method is used to find the length of the dictionary or in other words, it calculates the number of key-value pairs. It counts the key-value pair as one.

len(dict_name)
tech = { 'I': 1, 'DL': 2, 'ML': 3, 'RL':0, 'DS': 4 }
len (tech)
5

Python dictionary copy () method

The copy () method is used to copy a complete dictionary. You can also use another variable to hold this copy. This is required sometimes when you don’t want to mess with the original version of the dictionary.

dict_name.copy()
tech = { 'I': 1, 'DL': 2, 'ML': 3, 'RL':0, 'DS': 4 }
tech2 = tech.copy()
print (tech2)
{ 'I': 1, 'DL': 2, 'ML': 3, 'RL':0, 'DS': 4 }

Python dictionary clear () method

The clear () method is used to clear (or delete) all the elements (key-value pair) of the dictionary, thus leaving behind an empty dictionary. The dictionary still exists but without any elements in it.

dict_name.clear()
tech2= { 'I': 1, 'DL': 2, 'ML': 3, 'RL':0, 'DS': 4 }
tech2.clear ( )
print (tech2)
{ } # an empty dictionary

To delete a dictionary in Python

In the previous section, you have learned to delete a specific element from the dictionary using del. You had used del keyword followed by name of the dictionary and inside square bracket the name of the key. 

To completely delete a dictionary, you can use the del keyword followed by just name of a dictionary as shown below.

del dict_name
tech2= { 'I': 1, 'DL': 2, 'ML': 3, 'RL':0, 'DS': 4 }
del tech2
print (tech2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'tech2' is not defined

Conclusion

After reading the complete tutorial, you have understood about dictionary in python. You have understood why we need the dictionary despite having other data structures like List, Tuple and Set. You have learned to create, modify, update and delete the elements (key-value pair) from a dictionary. You have also learned about various methods used in a dictionary such as get, fromkeys, setdefaults and many others.

You have acquired a lot of knowledge on Python dictionaries. Now it’s time to practice it.

Keep Learning and Keep Growing !!

How did you like the content