Python Dictionary Object Example

Let's learn how to work with python dictionary, dictionary is a collection object, here we see examples of how to create a python dictionary object, how python dictionary works, what are the built-in methods in dictionary object, and what type of data we can store in a dictionary object.

Dict = {'Course' : 'Python', 10: [14,4.5,.60], 'Provider' : 'WebTrainingRoom'} 

Python Dictionary is a collection type object, which can store data using keay value “key:value” pair, in this article we will learn how to work with Python dictionary object.

We can create python dictionary object different ways, here are few examples.

class DictionaryExample(object):
   
    def __init__(self):
         self.Title = "Dictionary Examples";
    
    def showFunction(obj):
        Dict = {"Course:Python"} 
        print("New Dictionary created") 
        print(Dict)

Create new instance of dictionary in python

We cannot create a new instance of dictionary object in python, because when we add data to python dictionary object, earlier data is overwritten!

To create a list of object from python dictionary, we need to take help of a class, so we can create a new instance of a class and add that to list object

Take a look at the example below!

d1 = {"title": 'title1', "description":'description1'}
d1["title"] = "title will appear here"
d1["description"] ="some description here"

Now we create a class called "Study"!

class Study(object):

    def __init__(self,dictionary):        
        self.title=dictionary["title"]  
        self.description=dictionary["description"]

Now we create a new instance of class object and add dictionary data into the list object!

studyList[]

# adding new data to dict object
d1["title"] = "title 100 will appear here"
d1["description"] ="description 100 here"
m= Study(d1)                                  
studyList.append(m)

Example of looping through Dictionary Items

tr= {'name': 'Venezuela', 'continent': 'South America', 'region': 'South America'}

for item in tr.items():
    print(item)

#result 
('name', 'Venezuela')
('continent', 'South America')
('region', 'South America')
OR
for key in tr:
print(key, "->", tr[key])
#result
name -> Venezuela
continent -> South America
region -> South America

Python dictionary functions tutorial

We can create dictionary object with different type of keys, but we must make sure providing right key at the time of retrieval

Dict = {'Course' : 'Python', 10: [14,4.5,.60], 'Provider' : 'WebTrainingRoom'} 
print(Dict)

We also can create dictionary with dict() method.

Dict = dict({1: 'Red', 2: 'Green', 3:'Blue'}) 
print(Dict) 
Python Dictionary Methods

Here are some python dictionary methods with examples.

  1. Removes all the elements from the dictionary, make it empty. clear()
    Dict = dict({1: 'Red', 2: 'Green', 3:'Blue'}) 
    Dict.clear(); 
    print(Dict) 
    
  2. Copy a dictionary object with data to a new dictionary object. copy()
    d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'}) 
    d2=d1.copy(); 
    print(d2) 
    
  3. Get all keys of a dictionary object, useful when you want to retrieve value by using a key. keys()
    d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'}) 
    allkeys=d1.keys(); 
    
  4. popitem() : Pick the last item from the dictionary
    d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'}) 
    d2=d1.popitem(); 
    print(d2);
    #result : (3, 'Blue')
    
  5. Pick the Specified item based on given key from the dictionary, if no matching key found then it throws error. pop()
    d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'}) 
    d2=d1.pop(2); 
    print(d2);
    #result : ('Green')
    
  6. Insert an item to the dictionary object; update python dictionary with new item. update()
    d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'}) 
    d1.update({"color": "Orange"}); 
    print(d1) 
    #result : {1: 'Red', 2: 'Green', 3:'Blue', "color": "Orange"} 
    
  7. Get all values of a dictionary object, useful when you want to retrieve all values. values()
    d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'}) 
    allValues=d1.values(); 
    
  8. There is no direct method for sorting a dictionary collection in python, but we can make a list object of all keys in dictionary, then we can sort the key-list, here is an example of how to sort a dictionary object in python. sort()
    Dict  = dict({"India": 'Delhi', "Uk": 'London', "USA":'Washington'})         
    lst1=list(Dict.keys());
    lst1.sort();
    for K in lst1:
        print(":".join((K,str(Dict[K]))));
    
  9. this method is to find the length of a dictionary collection in python. len()
    Dict  = dict({"India": 'Delhi', "Uk": 'London', "USA":'Washington'}) 
    print("Length : %d" % len (Dict))
    
  10. this will form a string from given dictionary object. str()
    Dict  = dict({"India": 'Delhi', "Uk": 'London', "USA":'Washington'})
    print(str(Dict))
    

After using dictionary object, we can finally delete the dictionary using "del" key word.

country =	{
"name": "India",
"game": "Cricket",
  "river": "Ganga"
}
del country

Python dictionary is just like generic list object that allow us to store values with key, we can add , remove any number of items, we can retrieve item by using key.

 
Python dictionary Object
Learn python programming with free python coding tutorials.
Other Popular Tutorials
Python dictionary functions
Python programming examples | Join Python Course