View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

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

By Rohit Sharma

Updated on Dec 21, 2023 | 8 min read | 6.2k views

Share:

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.

background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree18 Months

Placement Assistance

Certification8-8.5 Months

Frequently Asked Questions (FAQs)

1. What can be stored in a Python dictionary?

2. How are Hashtable and Dictionary different?

Rohit Sharma

711 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

18 Months

upGrad Logo

Certification

3 Months