Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Python Dictionary: Everything You Need To Know [With Examples]

Updated on 21 December, 2023

6.08K+ views
8 min read

If you’re working with Python, you must have heard of lists, strings, and tuples. Today, we’re going to talk about another crucial element of Python – dictionary. After you’re done reading this post, you should have a relatively good understanding of Python dictionaries, how to create them, and how to use them. 

What is a Python Dictionary?

In Python, a dictionary is an implementation of a data structure that is usually known as an associative array. It contains an unorganized collection of data values (for example, a map). However, unlike other data types that contain only a single value as an element, the data values stored in a dictionary hold a key:value pair. This helps optimize the dictionary. Each key: value pair maps the unique key associated with its value. 

In a Python dictionary, keys are unique, but the values may or may not be – while the keys must be of an immutable data type (strings, numbers, and tuples), values can be of any type. Also, in a Python dictionary, the keys are case sensitive. So, keys having the same name, but different cases are treated differently.  

Learn more about: Python Data Types

Learn data science course from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Dictionary vs. Lists

In Python, dictionaries and lists share both similarities and differences. The common traits shared by dictionaries and lists include:

  • They are mutable.
  • They are dynamic.
  • They can nest – a list can contain another list and a dictionary can contain another dictionary. Also, a list can hold a dictionary and vice versa.

The main difference between dictionaries and lists is that while list elements can be accessed (based on their position in the list) via indexing, dictionary elements are accessed via keys.

Check out All Python tutorial concepts Explained with Examples.

Python Dictionary – Methods

Now, we’ll discuss some of the most commonly used methods in Python dictionaries.

  • copy( ) – It returns a shallow copy of a dictionary.
  • clear( ) – It removes all the items from a dictionary.
  • type( ) – It returns the type of the passed variable.
  • pop( ) – It removes and returns an item from a dictionary after the key is provided.
  • popitem( ) – It removes and returns an arbitrary item (key, value). Also, it raises KeyError if the dictionary is empty. 
  • get( ) – It is used to access the value for a key.
  • items( ) – It returns a new view of the dictionary’s items (key, value).
  • str( ) – It generates a printable string representation of a dictionary.
  • pop(key[,d]) – It removes the item with key and returns its value, and if key is not found, it returns d. However, if d is not provided and the key isn’t found, it returns KeyError. 
  • get(key[,d]) – It returns the value of key. If the key does not exist, it returns d (defaults to None). 
  • fromkeys(seq[, v]) – It returns a new dictionary with keys from seq and the value equals v (defaults to None).
  • update([other]) – It updates the dictionary with the key/value pairs from other by overwriting the existing keys.
    upGrad’s Exclusive Data Science Webinar for you –

     

     

How to create a dictionary?

  • You can create a Python dictionary by enclosing a comma-separated list of key-value pairs in curly braces { }. A colon “:” separates each key from its associated value:

    d = {
    
        <key>: <value>,
    
        <key>: <value>,
    
          .
    
          .
    
          .
    
        <key>: <value>
    
    }
    
    You can also use the built-in function dict( ) to create a dictionary, like so:
    
    # empty dictionary
    
    my_dict = {}
    
    # dictionary with integer keys
    
    my_dict = {1: ‘apple’, 2: ‘ball’}
    
    # dictionary with mixed keys
    
    my_dict = {‘name’: ‘John’, 1: [2, 4, 3]}
    
    # using dict()
    
    
    my_dict = dict({1:’apple’, 2:’ball’})
    
    # from sequence having each item as a pair
    
    my_dict = dict([(1,’apple’), (2,’ball’)])

How to access elements from a dictionary?

  • To access an element from a dictionary, you must refer to its key name. You can use the get( ) method to retrieve the item, or you can mention the key name inside a square bracket [ ]. If a key isn’t found in the dictionary, the get( ) method returns None instead of KeyError. 
  • Here’s an example of a code used to access elements from a dictionary:

    #!/usr/bin/python
    
    dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
    
    print “dict[‘Name’]: “, dict[‘Name’]
    
    print “dict[‘Age’]: “, dict[‘Age’]
    
  • Our learners also read: Top Python Free Courses

How to add or change elements in a dictionary?

  • Since Python dictionaries are mutable, you can add elements or even change the values of the existing items contained in a dictionary. Elements can be added to a dictionary in many ways. However, you can add one value to the dictionary at one time by defining it along with its key.
  • For example, dict[key] = ‘value’. To update an existing value in a dictionary, you have to use the built-in update( ) method. You must remember that while adding a value to a dictionary if the value already exists, the value gets updated otherwise a new key with the value is added to the dictionary.

    my_dict = {‘name’:’Jack’, ‘age’: 26}
    
    # update value
    
    my_dict[‘age’] = 27
    
    #Output: {‘age’: 27, ‘name’: ‘Jack’}
    
    print(my_dict)
    
    # add item
    
    my_dict[‘address’] = ‘Downtown’  
    
    # Output: {‘address’: ‘Downtown’, ‘age’: 27, ‘name’: ‘Jack’}
    
    print(my_dict)

How to remove or delete elements from a dictionary?

To remove or delete an item from a dictionary, you can use the pop ( ) method. It will remove the particular item with the provided ket and return the value. You can also use the popitem( )method to delete and return an arbitrary element (key and value) from the dictionary.

If you want to delete all the items at once, you can use the clear( ) method. You can also use the del keyword to remove individual items or the del dict ( ) method to delete the entire dictionary itself.

An example using the del dict ( ) method:

#!/usr/bin/python

dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}

del dict[‘Name’]; # remove entry with key ‘Name’

dict.clear(); # remove all entries in dict

del dict ; # delete entire dictionary

print “dict[‘Age’]: “, dict[‘Age’]

print “dict[‘School’]: “, dict[‘School’]

Also learn: Python Developer Salary in India

How to loop through a dictionary?

In a Python dictionary, you can loop through using a for loop. When you loop through a dictionary, the keys of the dictionary are the return value.

An example of looping through a dictionary is:

for x in thisdict:

print(x)

Read: Most Important Python Functions

How to check if a key is present in a dictionary?

You can use the “in” keyword to check if a specific key is present in the dictionary, like so:

thisdict = {
  “brand”: “Ferrari”,
  “model”: “Daytone”,
  “year”: “1968”
}

if “model” in thisdict:

print(“Yes, ‘model’ is one of the keys in the thisdict dictionary”)

How to determine the length of a dictionary?

You can set the length of a dictionary, that is, determine how many elements (key:value pairs) it will have, using the len( ) method, like so:

print(len(thisdict))

How to copy a dictionary?

You can copy a dictionary using the built-in copy( ) method. However, you cannot copy a dictionary by typing dict2 = dict1 because dict2 will only be a reference to dict1.

Here’s an example using the copy( ) method: 

thisdict = {
  “brand”: “Ford”,
  “model”: “Mustang”,
  “year”: 1964
}

mydict = thisdict.copy()

print(mydict)

Python Dictionary: Comprehension

In Python, dictionary comprehension is a straightforward and neat way of creating a new dictionary from an iterable. It consists of an expression pair (key: value) followed by for statement inside curly braces { }. Dictionary comprehension can contain multiple for or if statements.

Here’s an example for creating a dictionary where each item is a pair of a number and its square:

squares = {x: x*x for x in range(6)}

# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

print(squares)

Read more: Python Data Visualization Libraries

Wrapping up

That’s it basically – all the fundamental knowledge you need to know about Python dictionary!

If you are curious to learn about Python, everything about Data science, check out upGrad’s Data Science Certification Courses which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Frequently Asked Questions (FAQs)

1. What can be stored in a Python dictionary?

Dictionaries are utilized in Python for retrieving data with the help of any unique key. Everything that you can store in a Python variable could be stored in a Python dictionary. You can even nest one dictionary into another by creating lists. In contrast, the keys have to be immutable.

You can easily retrieve the stored value by calling the key that is storing the particular value. If you make any changes to the returned list, then it will also be impacted on the dictionary. One needs to understand that the values stored in the dictionary and the retrieved list are just the same objects.

2. How are Hashtable and Dictionary different?

A Hashtable is a non-generic collection, while a Dictionary is a generic collection of data values. You are allowed to store the key-value pairs of the same as well as of different data types, while you can only store the same data type key-value pairs in a dictionary.

As there is boxing and unboxing in Hashtable, the data retrieval process is slower as compared to Dictionary. There is no order maintained in a Hashtable, but you will always see a maintained order of the stored values in a Dictionary.