Programs

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.

Explore our Popular Data Science Courses

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.

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

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.

What 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.

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.

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.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Data Science Course

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Let’s do it!
No, thanks.