DICTIONARY IN PYTHON

machine learning from scratch

In today’s tutorial of data types in python, we are going to learn about dictionary in python. Dictionary, a pair of values, one being the Key and the other corresponding pair element being its Key: value, is collection of unordered, indexed and mutable data values. It is generally used when we have a huge amount of data. Python dictionaries are written with curly brackets { } with each item being a pair in the form key:value. A dictionary in python is also defined as an associative array or hash table that contains objects indexed by keys.

 >>> a = { 
    'name' : 'Diwas',
    'age' :  13}
>>> print(type(a))

output :
<class 'dict'>

We can access the data items of dictionary in python by referring to its key name, inside square brackets. get() method can also be used to access the item.

>>> b = { 
    'name' : 'sunil',
    'age' : 23,
    'height': 5.4
}
>>> print (b['age'])
>>> print (b.get('age'))

output :
23
23
When we use get( ) :

When we tried to access key that is not present in dictionary using square bracket, it throws error. To avoid this problem we use get ( ) method. Get simply returns the non value which means the object that represents the absence of a value. Also, we can pass the default value instead of getting none as result :

>>> age = {
          'a' : 1,
          'b' : 2
      }
>>> print (age.get('c'))
>>> print ('after passing default key value ',age.get('c', 3)

output:
None
after passing default key value 3

Although strings are the most common type of key, you can use many other Python objects, including numbers and tuples. Some objects, including lists and dictionaries,cannot be used as keys because their contents can change.

SET VS DICTIONARY IN PYTHON

While this both data type use same bracket to define each other, the main difference is that set is collection on unique keys (does not actually contain values), which is useful for doing set operations. Reference object in dictionary is called key while data is the value. The key can be string or number but the value can be number, string, a boolean, a list anything.

>>> student = {
        "name":"Diwas Pandey",
        "College ID": 1929635,
        "Phone number" : 9898989898,
        "Email ID" : "diwaspandey@gmail.com",
        "Address": "Kathmandu"
         }

What if we add another key value pair with same key ?? Any attempt to use the same key again will simply delete the previous stored value which means each key in a dictionary should be unique. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.

Dictionaries are mutable :

Dictionaries are mutable. Once a dictionary is created, its value can be changed by refering its key name. Lets take an example : There is a student named sushmita in a college from CSIT faculty. She lives in USA . & her age is 21 years. Lets define a dictionary with this information.

 >>> student = { 
    'name':'sushmita',
    'faculty':'CSIT',
    'age':22,
    'location':'USA'}
>>> print (student)

output:
{'name': 'sushmita', 'faculty': 'CSIT', 'age': 22, 'location': 'USA'}

Oh sorry ! We entered wrong information on age. What should we do now?? There is a way :

>>> student['age']=21
>>> print (student)

output:
{'name': 'sushmita', 'faculty': 'CSIT', 'age': 21, 'location': 'USA'}

Above dictionary consists of information of a student like name, faculty, age and location. Now we need to add gender as well. To add new item to the dictionary, we need to assign a new index key and value to it:

>>> student['gender']= 'female'
>>> print (student)

output:
{'name': 'sushmita', 'faculty': 'CSIT', 'age': 21, 'location': 'USA', 'gender': 'female'}

Girls usually don’t share their age with other. Let’s remove her age from the dictionary. pop() method can be used to remove the item with the specified key name. The del keyword removes the item with the specified key name whereas clear() method empties the dictionary in python.

>>> student.pop('age')   #removes age
>>> print (student)
>>> del student['faculty']   #removes faculty
>>> print (student)
>>> student.clear()    # empties all dictionary
>>> print (student)

OUTPUT:
{'name': 'sushmita', 'faculty': 'CSIT', 'location': 'USA', 'gender': 'female'}
{'name': 'sushmita', 'location': 'USA', 'gender': 'female'}
{}

An empty dictionary in python is created in one of two ways:

>>> d = {}
>>> e = dict()
Nested Dictionary In Python

Lets create nested dictionary named student which contains information of all the students in a class.

>>> college = {
    "std1" : {
    "name" : "A",
    "year" : 2002
  },
  "std2" : {
    "name" : "B",
    "year" : 2009
  },
  "std3" : {
    "name" : "C",
    "year" : 2018
  }
} 

We have another way to create nested dictionary in python. First we can create three different dictionaries , then we can create single dictionary including all three different dictionaries. Here is the example:

>>> std1 = {
    "name" : "A",
    "year" : 2002
  }
>>> std2 = {
    "name" : "B",
    "year" : 2009
  }
>>> std3 = {
    "name" : "C",
    "year" : 2018
  }

Lets combine all three dictionaries and create a single nested dictionary in python.

>>> college = {
  "std1" : std1,
  "std2" : std2,
  "std3" : std3
}
METHODSFUNCTION
clear( )Removes all the elements from the dictionary
copy( )Returns a copy of the dictionary
fromkeys( )Returns a dictionary with the specified keys and value
get( )Returns the value of the specified key
items( )Returns a list containing a tuple for each key value pair
keys( )Returns a list containing the dictionary’s keys
pop( )Removes the element with the specified key
popitem( )Removes the last inserted key-value pair
update( )Updates the dictionary with the specified key-value pairs
values( )Returns a list of all the values in the dictionary

This page is contributed by Diwas & Sunil . If you like AIHUB and would like to contribute, you can also write an article & mail your article to  itsaihub@gmail.com . See your articles appearing on AI HUB platform and help other AI Enthusiast.

About Diwas Pandey

Highly motivated, strong drive with excellent interpersonal, communication, and team-building skills. Motivated to learn, grow and excel in Data Science, Artificial Intelligence, SEO & Digital Marketing

View all posts by Diwas Pandey →

One Comment on “DICTIONARY IN PYTHON”

  1. Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something.
    I think that you can do with some pics to drive the message home
    a bit, but instead of that, this is magnificent blog.
    A fantastic read. I will certainly be back.
    adreamoftrains best web hosting company

Leave a Reply

Your email address will not be published.