PDA Assignments
  • Python For Data Analytics
    • 1.Python
      • 1.Python Documents
        • 1.Data Types
        • 2.Variables In Python
        • 3.Operators In Python
        • 4.User Input In Python
        • 5.TypeCasting In Python
        • 6.Strings In Python
        • 7.Conditional Statements In Python
        • 8.Branching using Conditional Statements and Loops in Python
        • 9.Lists In Python
        • 10.Sets In Python
        • 11.Tuples In Python
        • 12.Dictionary In Python
        • 13.Functions In Python
        • 14.File Handling In Python
        • 15.Numerical Computing with Python and Numpy
      • 2.Python Assignments
        • Data Type & Variables
        • Operators Assignment
        • User Input & Type Casting
        • Functions- Basic Assignments
        • String Assignments
          • String CheatSheet
        • Conditional Statements Assignments
        • Loops Assignments
        • List Assignments
          • List Cheatsheet
        • Set Assignments
          • Sets Cheatsheet
        • Dictionary Assignments
          • Dictionary Cheatsheet
        • Function Assignments
        • Functions used in Python
      • 3.Python Projects
        • Employee Management System
        • Hamming distance
        • Webscraping With Python
          • Introduction To Web Scraping
          • Importing Necessary Libraries
          • Basic Introduction To HTML
          • Introduction To BeautifulSoup
          • Flipkart Web Scraping
            • Scraping Step By Step
        • Retail Sales Analysis
        • Guess the Word Game
        • Data Collection Through APIs
        • To-Do List Manager
        • Atm-functionalities(nested if)
        • Distribution of Cards(List & Nested for)
        • Guess the Number Game
      • 4.Python + SQL Projects
        • Bookstore Management System
    • 2.Data Analytics
      • 1.Pandas
        • 1.Pandas Documents
          • 1.Introduction To Pandas
          • Reading and Loading Different Data
          • 2.Indexing and Slicing In Pandas
          • 3.Joining In Pandas
          • 4.Missing Values In Pandas
          • 5.Outliers In Pandas
          • 6.Aggregating Data
          • 7.DateTime In Pandas
          • 8.Validation In Pandas
          • 9.Fetching Data From SQL
          • 10. Automation In Pandas
          • 11.Matplotlib - Data Visualization
          • 12. Seaborn - Data Visualization
          • 13. Required Files
        • 3.Pandas Projects
          • Retail Sales Analysis
            • Retail Sales Step By Step
          • IMDB - Dataset Analysis - Basic
        • 2. Pandas Assignments
          • 1. Reading and Loading the Data
          • 2. Data frame Functions and Properties
          • 3. Series - Basic Operations
          • 4. Filtering in Pandas
          • 5. Advance Filtering
          • 6. Aggregate Functions & Groupby
          • 7. Pivot Tables
          • 8. Datetime
          • 9. String Functions
Powered by GitBook
On this page
  • What is Dictionary?
  • Keys Must be immutable:
  • Properties of a Dictionary :
  • Ordered :
  • Mutable:
  • Does not allow duplicate Keys:
  • Functions used in Dictionaries :
  • How to access values from a dictionary :
  • How to change values in a dictionary :
  • How to add values in a Dictionary :
  • Dictionary Methods :
  • keys() :
  • values():
  • items() :
  • Iteration in keys of dictionaries:
  • Iteration in values of dictionaries:
  • Iteration of key-value pair or items in dictionaries:
  • How to create dictionary with user inputs:
  • how to add an iterables items in a dictionaries: update()
  • Remove items from Dictionary :
  • pop() method :
  • popitem() :
  • setdefault :
  • clear() :
  • copy() :
  • dict():
  • Assignment:
  1. Python For Data Analytics
  2. 1.Python
  3. 1.Python Documents

12.Dictionary In Python

What is Dictionary?

Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python, which can simulate the real-life data arrangement where some specific value exists for some particular key. It is the mutable data-structure. The dictionary is defined into element Keys and values.

  • Keys must be an immutable element.

  • Value can be any type such as list, tuple, integer, etc.

In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.

A Dictionary is enclosed under curly braces {}. For Example:

In [1]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}

print(employee)
{'name': 'Abhi', 'role': 'Trainer'}

In above dictionary , Key 'name' holds 'Abhi' value .

Keys Must be immutable:

Keys in Dictionary must be immutable elements like numbers , strings , tuple etc. It will throw an error if key is a mutable element.

Properties of a Dictionary :

Ordered :

Dictionaries do not have index numbers but still it has keys, hence dictionaries are ordered. For Example:

In [2]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}

print(employee)
{'name': 'Abhi', 'role': 'Trainer'}

Mutable:

Dictionaries are mutable or changeable. We can change values of dictionary elements with the help of keys. For Example :

In [3]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}

employee['name'] = "Smith"

print(employee)
{'name': 'Smith', 'role': 'Trainer'}

Does not allow duplicate Keys:

If there is more than one key-value pair with same key , Dictionary will store only last inserted Key-Value pair. For Example:

In [5]:

employee = {"name" : "Abhi",
            "name" : "Abhishek",
            "role" : "Trainer",
}

print(employee)
{'name': 'Abhishek', 'role': 'Trainer'}

Functions used in Dictionaries :

Functions like max() , min() and len() works on sequence .

In [6]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}
max(employee)  #max() works on keys.

In [7]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}
min(employee)  #min() works on keys.

In [9]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}
len(employee)  

How to access values from a dictionary :

We can access values of dictionary with the help of keys , same as we do with the help of index in list.

In [10]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}

value = employee["role"]
print(value)

How to change values in a dictionary :

To change value of a dictionary we will simply assign new value to its key. For Example:

In [11]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}

employee['role'] = "Senior Trainer"

print(employee)
{'name': 'Abhi', 'role': 'Senior Trainer'}

How to add values in a Dictionary :

We can add values in a dictionary simply by assigning a new value in a new key. For Example :

In [12]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}

employee["Course"] = "Data Science"

print(employee)
{'name': 'Abhi', 'role': 'Trainer', 'Course': 'Data Science'}

Dictionary Methods :

Functions that are specific to dictionary are known as dictionary methods. We will go through each method one by one.

keys() :

keys() method return a sequence of keys. For example :

In [13]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}

k = employee.keys()

print(k)
dict_keys(['name', 'role'])

values():

values() method return a sequence of values. For Example:

In [14]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}

k = employee.values()

print(k)
dict_values(['Abhi', 'Trainer'])

items() :

items() method returns tuple of key-value pairs in a sequence. For Example:

In [15]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
}

i = employee.items()
print(i)
dict_items([('name', 'Abhi'), ('role', 'Trainer')])

Iteration in keys of dictionaries:

Below example is to show you how to iterate keys of dictionaries :

In [16]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
            "course" : "data science",
            "duration" : 3
}

for k in employee.keys():
    print(k)
name
role
course
duration

We can also iterate keys of dictionaries simply iterating dictionary only. For Example:

In [17]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
            "course" : "data science",
            "duration" : 3
}

for k in employee.keys():
    print(k)
name
role
course
duration

Iteration in values of dictionaries:

employee = {"name" : "Abhi",
            "role" : "Trainer",
            "course" : "data science",
            "duration" : 3
}

for v in employee.values():
    print(v)
Abhi
Trainer
data science
3

Iteration of key-value pair or items in dictionaries:

Below example is to show you how to iterate key-value pair or items in dictionaries . It returns a tuple.

In [19]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
            "course" : "data science",
            "duration" : 3
}

for i in employee.items():
    print(i)
('name', 'Abhi')
('role', 'Trainer')
('course', 'data science')
('duration', 3)

We can also separate keys and values from with the help of this code.

In [22]:

employee = {"name" : "Abhi",
            "role" : "Trainer",
            "course" : "data science",
            "duration" : 3
}

for k,v in employee.items(): #k holds keys and v holds values.
    print(f'{k} holds {v}')
name holds Abhi
role holds Trainer
course holds data science
duration holds 3

How to create dictionary with user inputs:

To create a dictionary with user inputs , we may ask keys and values from user and add them in an empty dictionary. For Example:

In [23]:

mydict = {}

for i in range(5):
    k = input("Enter Key : ")
    v = input("Enter Values : ")
    mydict[k] = v

print(mydict)
Enter Key : name
Enter Values : abhi
Enter Key : role
Enter Values : trainer
Enter Key : course
Enter Values : data science
Enter Key : duration
Enter Values : 3
Enter Key : projects
Enter Values : 50
{'name': 'abhi', 'role': 'trainer', 'course': 'data science', 'duration': '3', 'projects': '50'}

how to add an iterables items in a dictionaries: update()

update() method adds items (key value pair) from an iterable in a dictionary. For Example:

In [24]:

thisdict = {'name': 'abhi',
            'role': 'trainer',
            'course': 'data science',
            'duration': '3',
            'projects': '50'
           }

anotherdict = {"company" : "console flare",
               "location" : "Noida"
    
} 

thisdict.update(anotherdict) 

print(thisdict)
{'name': 'abhi', 'role': 'trainer', 'course': 'data science', 'duration': '3', 'projects': '50', 'company': 'console flare', 'location': 'Noida'}

You can also update items from list or tuple or sets in a dictionary. But the only condition is it should be in key value form. A simple list cannot be converted in a dictionary. For Example :

In [2]:

thisdict = {'name': 'abhi',
            'role': 'trainer',
            'course': 'data science'
           }

thislist = [1,2,3,4,5]
thisdict.update(thislist)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-6bd84fe955ce> in <module>
      5 
      6 thislist = [1,2,3,4,5]
----> 7 thisdict.update(thislist)

TypeError: cannot convert dictionary update sequence element #0 to a sequence

hence we can only update items of an iterable that are in key value pair. So how can a list items be updated in dictionary.

What will happen if i convert a set items in a list using dict() constructor.

In [3]:

thisdict = {'name': 'abhi',
            'role': 'trainer',
            'course': 'data science'
           }

newlist = list(thisdict.items())
print(newlist)
[('name', 'abhi'), ('role', 'trainer'), ('course', 'data science')]

Now , above list is in form of key value pair. if we want to convert list items in a dictionary , our list should have tuples as list items with key value pair in it. For Example:

In [4]:

newlist = [('name', 'abhi'), ('role', 'trainer'), ('course', 'data science')]

newdict = dict(newlist)
print(newdict)
{'name': 'abhi', 'role': 'trainer', 'course': 'data science'}

Remove items from Dictionary :

There are various methods to remove items from dictionary. We will go through each method step by step.

pop() method :

Removes the element with the specified key.

The pop() method removes the specified item from the dictionary.

The value of the removed item is the return value of the pop() method, see example below.

In [8]:

thisdict = {'name': 'abhi',
            'role': 'trainer',
            'course': 'data science'
           }

deleted_value = thisdict.pop('role')
print(thisdict)
print(f'deleted value is {deleted_value}')
{'name': 'abhi', 'course': 'data science'}
deleted value is trainer

popitem() :

The popitem() method removes the item that was last inserted into the dictionary.

The removed item is the return value of the popitem() method, as a tuple, see example below.

In [9]:

thisdict = {'name': 'abhi',
            'role': 'trainer',
            'course': 'data science'
           }

deleted_item = thisdict.popitem()
print(thisdict)
print(f'deleted value is {deleted_item}')
{'name': 'abhi', 'role': 'trainer'}
deleted value is ('course', 'data science')

setdefault :

Returns the value of the specified key. If the key does not exist: insert the key, with the specified value.

Syntax : dictionary.setdefault(keyname, value)

In [11]:

thisdict = {'name': 'abhi',
            'role': 'trainer',
            'course': 'data science'
           }

thisdict.setdefault("role", "not known")

print(thisdict)
{'name': 'abhi', 'role': 'trainer', 'course': 'data science'}

In above code we have set default value of role is 'not known' . So if role key does not exist in dictionary or is removed. default key value pair will be added in dictionary. For Example.

In [12]:

thisdict = {'name': 'abhi',
            'course': 'data science'
           }

thisdict.setdefault("role", "not known")

print(thisdict)
{'name': 'abhi', 'course': 'data science', 'role': 'not known'}

clear() :

clear method clears all the data in dictionary. for example:

In [13]:

thisdict = {'name': 'abhi',
            'role': 'trainer',
            'course': 'data science'
           }

thisdict.clear()

print(thisdict)

copy() :

copy() method is used to copy contents of a dictionary to another dictioary.For Example:

In [14]:

thisdict = {'name': 'abhi',
            'role': 'trainer',
            'course': 'data science'
           }

thisdict.clear()

print(thisdict)
{'name': 'abhi', 'role': 'trainer', 'course': 'data science'}

dict():

dict() constructor is used to convert a sequence in a dictionary. for Example:

In [7]:

newset = {('name', 'abhi'), ('role', 'trainer'), ('course', 'data science')}

newdict = dict(newset)
print(newdict)
{'name': 'abhi', 'role': 'trainer', 'course': 'data science'}

Assignment:

1.Write a Python script to merge two Python dictionaries 2.Write a Python program to iterate over dictionaries using for loops. 3.Write a Python program to remove a key from a dictionary. 4.Write a Python program to sort a given dictionary by key. 5.Write a Python program to get the maximum and minimum value in a dictionary. 6.Write a Python program to check multiple keys exists in a dictionary.

Previous11.Tuples In PythonNext13.Functions In Python

Last updated 11 months ago