Master Python Dictionary and its methods | 6 mins read

Python Dictionary
Python Dictionary
Python Dictionary and its methods is an important aspect Python programming. Dictionary datatype is used for membership testing or to count occurrence of an element in O(1) time complexity. Python Dictionary methods are often used to access, add or delete key:value pairs. Let's get started with today's Python tutorial.
Share This Post
Share on facebook
Share on linkedin
Share on twitter
Share on email
Share on reddit
Share on whatsapp

Table of Contents

Introduction

Welcome back to another exciting tutorial on “Python dictionary and its methods ”. In this Python tutorial, you’ll learn the methods of python dictionary and various operation that can be perform on them.

You’ll also learn how and when to use a specific dictionary method with the help of examples. In the end, you will see a python dictionary cheat sheet to quickly refresh what we learn so far. Let’s begin our tutorial with an introduction to the Python dictionary followed by its methods.

If you aren’t following along, I would recommend you to go back where you left or start from here.

What is Dictionary in Python ?

A datatype of a value is an attribute that signifies what type of data that variable holds.In Python, datatypes are objects of builtin classes so as python dictionary.

A Dictionary object is an unordered collection of key,value pair. A python dictionary is

  • Unordered – The place of elements is not fixed.So, it doesn’t support indexing or slicing.
  • Mutable– It does support operations like deletion and insertion of elements.
  • Key – Key is any immutable data type (such as string,numbers,tuples) which maps to a corresponding value.

Keys are case sensitive i.e ‘a’ and ‘A’ are considered as two different keys.

Key are unique.

Python Dictionary Methods

How to create Python Dictionary ?

There are several ways you can create a python dictionary either empty or having some initial key:value pairs.Let us understand every method one by one with sample code.

1.An empty dictionary – To create an empty dictionary there are two ways either using {} or dict() constructor.

People often get confused between set and dictionary creation using {}. The main difference is that you can create empty dictionary using {} but not empty set.

A set created using {} should contain atleast one value.

>>> dict1 = {}
>>> type(dict1)
<class 'dict'>

>>> dict1 = dict()
>>> type(dict1)
<class 'dict'>

2.Using literals for keys – Keys is unique and hashable .So int,string,char etc can be used as key . Also ,there can be keys of different datatype in same dictionary.

>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

3.Passing key-value as default argument in dictionary constructor.

count = dict(1 = one,2 = two,3 = three,4 = four)
print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

4.Using list of tuples – Each tuple in the list represent the key:value pair .

>>> iterable = [(1,one),(2,two),(3,three),(4,four)]
>>> count = dict(iterable)
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

5.Using list of keys mapped to a default value – This is a very useful way to create a dictionary when you know all the keys already. A default value is set to all the key using this method.

>>> subjects = ['English','Hindi','Mathematics','Science']
>>> grades = dict.fromkeys(subjects,0)
>>> print(grades)
{'English': 0, 'Hindi': 0, 'Mathematics': 0, 'Science': 0}

How to access a Python Dictionary ?

You can access dictionary value mapped to a key same as you access list by passing its index in square bracket.
Ex – dict1[key] gets you value at key ‘key’ in dict1.
There are several other methods discussed below:–

1.By direct passing key in square bracket – This is the simplest and trivial way to access a key in a dictionary.It will raise an error if key is not present.

>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> print(count[1])
one

2.Using get() method – Get method takes two parameter first is the key and second is the default return value in case key isn’t found.

>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> print(count.get(2))
one

# An example of using default value
>>> print(count.get(5,'not found'))
not found

3.Looping over all keys – To access each key in the dictionary you can use a simple for loop.

>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> for keys in count:
       print(keys,'---->',count[keys])
1 ----> one
2 ----> two
3 ----> three
4 ----> four

4.Using items() method – This method returns list of tuples which contain key:value pair.

>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> print(count.items())
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])

5.Using keys() method – The key method return the list of all keys present in dictionary.

>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> print(count.keys())
dict_keys([1, 2, 3, 4])

I use “for” loop and get method for accessing the keys.Mention in the comment section if you find any other method fascinating .

How to add new pair in Python Dictionary ?

Python Dictionary is a mutable datatype. We can modify the dictionary after initialization.There are several ways to perform this task:-

1.By direct passing key in square bracket – This method will create a new key:value pair .If key already exist its value will be updated.

>>> count= {1:'one',2:'two',3:'three',4:'four'}

2.Using update() method – Update method takes either dictionary or an iterable of key:value pair. It add those key:value pairs which aren’t present in the dictionary.

# Adding another dictionary
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> count2 = {5:'five',6:'six',7:'seven'}
>>> count.update(count2)
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven'}

# Update when tuple is passed
>>> count3 = [(8,'eight'),(9,'nine'),(10,'ten')]
>>> count.update(count3)
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'}

3.setdefault() method – This method is used for insertion of new pair.It has two argument

  • keyThe key name to be inserted
  • value(optional) If the key is already present, this argument isn’t used else it creates a new key with value given.

Return It return the value for the key

>>> count= {1:'one',2:'two',3:'three',4:'four'}

# Insert and return new key
>>> x = count.setdefault(5,'five')
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}

# Insert a key which is already present .Hence,value parameter do nothing.
>>> x = count.setdefault(1,'no change')
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}

How to delete key from Python Dictionary ?

1.Using pop(key,default ) – This method delete the specified key and return the value .

If key is not present and the defalut value is there,it is returned otherwise key error is raised.

>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> x = count.pop(4,'not found')
>>> print(x) 
four 
>>> print(count)
{1:'one',2:'two',3:'three'}
 
# Now 4 is removed 
>>> x = count.pop(4,'not found') 
>>> print(x) 
not found

2.Using popitem() method – It removes and return the last added key:value pair as tuple or raises key error if dictionary is empty.

>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> key,val = count.popitem()
>>> print(key,'--->',value)
4 ---> four

3.clear() method – This method delete all pair in the dictionary.

>>> count= {1:'one',2:'two',3:'three',4:'four'}

>>> count.clear()
>>> print(count)
(}

Cheat Sheet

Operationexplanation
len(d)
Number of key:value pairs.
key in d
Test membership of key in d.
d.copy()
Make a copy of given dictionary.
d.update(dict/iterable)
Update dictionary with key:value pairs.
d.setdefault(key,val)
Return value of given key.If key is not present insert the key with given val.
d.pop(key,default)
Remove and return the value of given key.If not present return default.
d.popitem()
Remove and return the last added pair as tuple.
d.clear()
Delete all the pairs of the dictionary.
d.get(key,default)
Return the value of key .If not present return default.
dict.fromkeys(iterable,val)
Return a dictionary with all keys present in iterable and value defined in val.
d.keys()
Return a list of all keys in d.
d.values()
Return a list of all values in d.
d.items()
Return a list of tuples containing key:value pair of d.
More To Explore
COBOL Tutorial
Machine Learning
COBOL Tutorial – COBOL Programming Tutorial. Free Curso de COBOL 60+

COBOL programming tutorial is design for absolute beginners. In this tutorial, cover most of the programming topic such as COBOL PERFORM STATEMENTS, COBOL REDEFINES Statements, COBOL Program Structure etc. Let’s get started with today’s COBOL Tutorial.