Attend FREE Webinar on Data Science for Career Growth Register Now

What is a Python Dictionary and How Does it Work?

5 (100%) 1 vote

Believe it or not, a Python dictionary works in a very similar way to a regular dictionary. Python offers many different data structures to hold information, and the dictionary is one of the simplest and most useful. While many things in Python are iterables, not all of them are sequences and a Python dictionary falls in this category. In this article, we will talk about what a Python dictionary is, how it works, and what are its most common applications.

What is a Python Dictionary?

Getting clean and actionable data is one of the key challenges in data analysis. You can’t build and fit models to data that isn’t usable. A Python dictionary makes it easier to read and change data, thereby rendering it more actionable for predictive modeling.

A Python dictionary is an unordered collection of data values. Unlike other data types which hold only one value as an element, a Python dictionary holds a key: value pair. The Python dictionary is optimized in a manner that allows it to access values when the key is known.

While each key is separated by a comma in a Python Dictionary, each key-value pair is separated by a colon. Moreover, while the keys of the dictionary have to be unique and immutable (tuples, strings, integers, etc), the key-values can be of any type and can also be repeated any number of times.

Here’s a video that discusses the basics of Python Dictionary as part of an overall Python tutorial.

Python Dictionary

Python Dictionary

How do Python Dictionaries Work?

While there are several Python dictionary methods, there are some basic operations that need to be mastered. We will walk through the most important ones in this section.

Python Dictionary

Python Dictionary Working

Creating a Python dictionary

To create a Python dictionary you need to put items (each having a key and a corresponding value expressed as key: value) inside curly brackets. Each item needs to be seperated from the nect by a comma. As discussed above, values can repeat and be of any type. Keys, on the other hand, are unique and immutable.  There is also a built-in function dict() that you can use to create a dictionary. Here’s are some examples :

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

Accessing Items within the Python dictionary

Accessing items in the dictionary in Python is simple enough. All you need to do is put the key name of the item within square brackets. This is important because the keys are unique and non-repeatable.

Example

To get the value of the model key:

x = thisdict[“model”]

You can also use another of the Python dictionary methods get() to access the item. Here’s what it looks like.

x = thisdict.get(“model”)

Change Values in a Python Dictionary

To change the value of an item, you once again need to refer to the key name. Here’s an example.

If you have to change the value for the key “year” from 1964 to 2019:

thisdict = {

 “brand”: “Ford”,

 “model”: “Mustang”,

 “year”: 1964

}

thisdict[“year”] = 2019

How to loop through a Python Dictionary

You can use a for loop function to loop through a dictionary in Python. By default, the return value while looping through the dictionary will be the keys of the dictionary. However, there are other methods that can be used to return the values.

To print the key names:

for x in thisdict:

 print(x)

To print the values in the dictionary, one by one:

for x in thisdict:

 print(thisdict[x])

Another way of returning the values by using the values() function :

for x in thisdict.values():

 print(x)

If you want to Loop through both the keys and the values, you can use the items() function:

for x, y in thisdict.items():

 print(x, y)

How to Check if a Key Exists in the Dictionary

Here’s how you can  determine whether a particular key is actually present in the Python dictionary:

Say you have to check whether the key “model” is present in the dictionary:

thisdict = {

 “brand”: “Ford”,

 “model”: “Mustang”,

 “year”: 1964

}

if “model” in thisdict:

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

How to Determine the number of items in the Dictionary

To determine the number of key : value pairs in the dictionary we use one of the most commonly used Python Dictionary methods,  len(). Here’s how it works:

print(len(thisdict))

How to add an item to the Python Dictionary

To add a new key: value pair to the dictionary, you have to use a new index key and then assign a value to it.

For instance,

thisdict = {

 “brand”: “Ford”,

 “model”: “Mustang”,

 “year”: 1964

}

thisdict[“color”] = “red”

print(thisdict)

Removing Items from the Python Dictionary

Here are some of the methods to remove an item from the Python dictionary. Each approaches the same goal from a different perspective.

Method 1

This method, pop(), removes the item which has the key name that is being specified. This works well since key names are unique and immutable.

thisdict = {

 “brand”: “Ford”,

 “model”: “Mustang”,

 “year”: 1964

}

thisdict.pop(“model”)

print(thisdict)

Method 2

The popitem() method removes the item that has been added most recently. In earlier versions, this method used to remove any random item. Here’s how it works:

thisdict = {

 “brand”: “Ford”,

 “model”: “Mustang”,

 “year”: 1964

}

thisdict.popitem()

print(thisdict)

Method 3

Much like the pop() method, the del keyword removes the item whose key name has been mentioned.

thisdict = {

 “brand”: “Ford”,

 “model”: “Mustang”,

 “year”: 1964

}

del thisdict[“model”]

print(thisdict)

Method 4

Unlike the pop() method, the del keyword can also be used to delete the dictionary altogether. Here’s how it can be used to do so:

thisdict = {

 “brand”: “Ford”,

 “model”: “Mustang”,

 “year”: 1964

}

del thisdict

print(thisdict) #this will cause an error because “thisdict” no longer exists.

Method 5

The clear() keyword empties the dictionary of all items without deleting the dictionary itself:

thisdict = {

 “brand”: “Ford”,

 “model”: “Mustang”,

 “year”: 1964

}

thisdict.clear()

print(thisdict)

Data Analytics Course by Digital Vidya

Free Data Analytics Webinar

Date: 25th Apr, 2019 (Thursday)
Time: 3 PM (IST/GMT +5:30)

A list of Common Python Dictionary Methods

There are a number of Python Dictionary methods that can be used to perform basic operations. Here is a list of the most commonly used ones.

Method

Description

clear()

This removes all the items from the dictionary

copy()

This method returns a copy of the Python dictionary

fromkeys()

This returns a different directory with only the key : value pairs that have been specified

get()

This returns the value of the key mentioned

items()

This method returns the a thuple for every key: value pair in the dictionary

keys()

This returns a list of all the Python dictionary keys in the dictionary

pop()

This removes only the key that is mentioned

popitem()

In the latest version, this method deletes the most recently added item

update()

This method updates the dictionary with certain key-value pairs that are mentioned

values()

This method simply returns the values of all the items in the list

What are the Advantages of a Dictionary in Python

Here are some of the major advantages of a Python library:

(i) It improves the readability of your code. Writing out Python dictionary keys along with values adds a layer of documentation to the code. If the code is more streamlined, it is a lot easier to debug. Ultimately, analyses get done a lot quicker and models can be fitted more efficiently.

(ii) Apart from readability, there’s also the question of sheer speed. You can look up a key in a Python dictionary very fast. The speed of a task like looking up keys is measured by looking at how many operations it takes to finish. Looking up a key is done in constant time vis-a-vis looking up an item in a large list which is done in linear time.

To look up an item in a huge list, the computer will look through every item in the list. If every item is assigned a key-value pair then you only need to look for the key which makes the entire process much faster. A Python dictionary is basically an implementation of a hash table. Therefore, it hs all the benefits of the hashtable which include membership checks and speedy tasks like looking up keys.

Python Dictionary

Python Dictionary Advantages

What are the Disadvantages of a Python dictionary

While a Python dictionary is easily one of the most useful tools, especially for data cleaning and data analysis, it does have a downside. Here are some disadvantages of using a Python dictionary.

(i) Dictionaries are unordered. In cases where the order of the data is important, the Python dictionary is not appropriate.

(ii) Python dictionaries take up a lot more space than other data structures. The amount of space occupied increases drastically when there are many Python Dictionary keys. Of course, this isn’t too much of a disadvantage because memory isn’t very expensive.

Conclusion

At the end of the day, a Python dictionary represents a data structure that can prove valuable in cleaning data and making it actionable. It becomes even more valuable because it is inherently simple to use and much faster and more efficient as well.

Of course, if you are looking for a career in data science, a comprehensive course with live sessions, assessments, and placement assistance might be just what you need.

A creative writer, capable of curating engaging content in various domains including technical articles, marketing copy, website content, and PR.

  • Data-Analytics

  • Your Comment

    Your email address will not be published.