HomeBlogData SciencePython Dictionary: Everything You Need To Know [With Examples]

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

Read it in 8 Mins

Last updated:
14th Apr, 2020
Views
1,500
In this article
View All
Python Dictionary: Everything You Need To Know [With Examples]

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.

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’)])

    Top Data Science Skills to Learn

    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)

 

Explore our Popular Data Science Courses

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

Read our popular Data Science Articles

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.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

1What is the need for dictionaries in Python?
An unordered collection of data values is a Python dictionary. Dictionaries are required in Python for storing data values just like a map. In all the other data types, they are only able to hold a single value as an element. But, a dictionary is able to hold the key:value pair. This pair makes the functioning of the dictionary a bit more optimized.

For creating a dictionary in Python, you simply need to place the elements within curly braces by separating all of them with a 'comma.' The values in the dictionary can be repeated and duplicated, but you cannot repeat the keys in the dictionary. The keys in a dictionary are case sensitive, so even two keys with the same name but different cases will be treated differently.
2What 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.
3How 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.

Suggested Blogs

Python Split Function: Overview of Split Function ()
1500
Introduction to the split() function in Python Split function in Python is a string manipulation tool that helps you to easily handle a big string in
Read More

by Rohit Sharma

25 May 2023

OLTP Vs OLAP: Decoding Top Differences Every Data Professional Must Know
1504
Several businesses use online data processing systems to boost the accuracy and efficiency of their processes. The data must be used before processing
Read More

by Rohit Sharma

12 Apr 2023

Amazon Data Scientist Salary in India 2023 &#8211; Freshers to Experienced
1500
Exploring Amazon Data Scientist Salary Trends in India: 2023 Data Science is not new; the International Association for Statistical Computing (IASC)
Read More

by Rohit Sharma

10 Apr 2023

Data warehouse architect: Overview, skills, salary, roles &#038; more
1500
A data warehouse architect is responsible for designing and maintaining data management solutions that support a business or organisation. They analys
Read More

by Rohit Sharma

10 Apr 2023

Research Scientist Salary in India 2023 &#8211; Freshers to Experienced
1500
Salary Trends for Research Scientists in India: 2023 From pharmacology to meteorology, the role of a Research Scientist across diverse domains implie
Read More

by Rohit Sharma

10 Apr 2023

Understanding Abstraction: How Does Abstraction Work in Python?
1500
Python is one of the most extensively used programming languages. Python has made it simple for users to program more efficiently with the help of abs
Read More

by Rohit Sharma

08 Apr 2023

Understanding the Concept of Hierarchical Clustering in Data Analysis: Functions, Types &#038; Steps
1502
Clustering refers to the grouping of similar data in groups or clusters in data analysis. These clusters help data analysts organise similar data poin
Read More

by Rohit Sharma

08 Apr 2023

Harnessing Data: An Introduction to Data Collection [Types, Methods, Steps &#038; Challenges]
1502
Data opens up the doors to a world of knowledge and information. As the currency of the information revolution, it has played a transformational role
Read More

by Rohit Sharma

08 Apr 2023

Top 50 Excel Shortcuts That Will Transform the Way You Work In 2023
1500
Microsoft Office has become a compulsory tool in almost every modern workplace. According to research, 81% of companies use MS Office and some of its
Read More

by Rohit Sharma

06 Apr 2023