Python Dictionary Tutorial with Examples

View more Tutorials:

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- Python Dictionary

In Python, dictionary is a data type and it is a list of elements, each of which is a pair of key & value. Dictinary quite similar to the Map concept in Java.
Dictionaries all are objects of the dict class.
In order to write a dictionary, you need to use { }, and write the elements into it, the elements are separated by comma. Each element is a pair of key and value separated by a colon ':'.

# Dictionary

myinfo =  {"Name": "Tran", "Age": 37, "Address" : "Vietnam"  }
You can also create a dictionary object from the constructor of the dict class.

# Create a dictionary via constructor of dict class.
mydict = dict()

mydict["E01"] =  "John"
mydict["E02"] =  "King"

print ("mydict: ", mydict)

Features of the value in the dictionary:

  • Each element of the dictionary is a pair of key and value, the value can be a certain type (string, number, user-defined types,...), and can be the same.

Features of the key in the dictionary.

  • The key in dictionary is a immutable type. So, it can be string, number, Tuple,...
  • Some types are not allowed (for example: List) because List is a mutable data type.
  • Key in dictionary is not allowed to duplicate.

# Dictionary

myinfo =  {"Name": "Tran", "Age": 37, "Address" : "Vietnam"  }

print ("myinfo['Name'] = ", myinfo["Name"])

print ("myinfo['Age'] = ", myinfo["Age"])

print ("myinfo['Address'] = ", myinfo["Address"])

2- Update Dictionary

Dictionary allows you to update the value of a certain key, it adds a new element if the key does not exist on the dictionary.

# Dictionary
myinfo =  {"Name": "Tran", "Age": 37, "Address" : "Vietnam"  }

# update value for key 'Address'
myinfo["Address"] = "HCM Vietnam"

# Add new element with key 'Phone'
myinfo["Phone"] = "12345"

print ("Element count: ", len(myinfo) )

print ("myinfo['Name'] = ", myinfo["Name"])

print ("myinfo['Age'] = ", myinfo["Age"])

print ("myinfo['Address'] = ", myinfo["Address"])

print ("myinfo['Phone'] = ", myinfo["Phone"])

3- Delete dictionary

There are 2 ways to remove an element from a dictionary.
  1. Use the del operator
  2. Using the "__delitem __ (key)" method

# (Key,Value) = (Name, Phone)
contacts = {"John": "01217000111", \
            "Tom": "01234000111", \
            "Addison":"01217000222", "Jack":"01227000123"}

print ("Contacts: ", contacts)

print ("\n")
print ("Delete key = 'John' ")

# Delete element with key 'John'
del contacts["John"]

print ("Contacts (After delete): ", contacts)

print ("\n")
print ("Delete key = 'Tom' ")

# Delete element with key 'Tom'
contacts.__delitem__( "Tom")

print ("Contacts (After delete): ", contacts)

print ("Clear all element")

# Clear all element

print ("Contacts (After clear): ", contacts)

# Delete dictionary 'contact' from memory
del contacts

# An error occured while accessing a variable that does not exist in memory
print ("Contacts (After delete): ", contacts)

4- Functions for Dictionary

Function Description

Return elements count of dict.


Produces a printable string representation of a dictionary


Returns the type of the passed variable. If passed variable is dictionary, then it will return the object representing the 'dict' class.

dir(clazzOrObject) Returns the members of the passed class (or object). If passed class is dict class, then it will return the members of dict class.

contacts = {"John": "01217000111" ,"Addison": "01217000222","Jack": "01227000123"}
print ("contacts: ", contacts)

print ("Element count: ", len(contacts) )

contactsAsString = str(contacts)

print ("str(contacts): ", contactsAsString )

# An object representing the 'dict' class.
aType = type(contacts)

print ("type(contacts): ", aType )

# dir(dict) function returns members of 'dict' class.
print ("dir(dict): ", dir(dict) )

# ------------------------------------------------------------------------------------
# ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', 
#  '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', 
#  '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', 
#  '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
#  '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 
#  'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 
#  'setdefault', 'update', 'values']
# -------------------------------------------------------------------------------------

5- Methods

  • TODO

View more Tutorials:

Maybe you are interested

These are online courses outside the o7planning website that we introduced, which may include free or discounted courses.