Learn Python Dictionary Data Structure – Part 3

In this Part 3 of Python Data Structure series, we will be discussing what is a dictionary, how it differs from other data structure in python, how to create, delete dictionary objects and methods of dictionary objects.

  • Dictionary is a built-in implementation of “Python Data Structure” which is a collection of “Key: Value” pairs.
  • Dictionary is created using curly braces with key and value separated by semicolon {Key : Value}.
  • Similar to list, dictionaries objects are mutable data type meaning objects can be modified once the dictionary is created.
  • The construct of dictionary implementation in python is more generally known as “Associative array”.
  • In list or tuples, we can access the items by referencing their index positions because items inside the list are ordered (i.e. Stored in the order they got created). The dictionary objects can be in any order since the items are accessed using its associated “Key”.
  • Dictionaries are very useful when we have to store the objects and refer them by name.
  • Dictionary “key” object must be a unique and immutable type.
  • Dictionary “Key” object can be either string, Integer, Floating values.
  • Dictionary “Values” can be of any data type.

Construct Dictionary Object

Dictionary object can be created using curly braces with semicolon separating key and value pair “{Key:value}” or “dict()” constructor method.

To demonstrate, I am going to create a dictionary that will store data about the football team and their playing XI with a position as key and player names as values.

Create Dictionary in Python
Create Dictionary in Python

You can use the constructor method dict() to construct a dictionary object.

Dictionary Constructor Method
Dictionary Constructor Method

Access Dictonary Object

Dictionary items are accessed by “key” references instead of indexing. It is possible to use indexing if we have any sequence data type (string, list, tuples, etc..) inside the dictionary.

Items can be accessed using dic_object[“key”].

Object Types
Object Types
Access Key Object
Access Key Object

KeyError” will be raised if you try to access dictionary items with indexing or if you try to access a “key” that is not part of dictionary.

KeyError
KeyError

Modify and Delete Dictionary Object

You can modify the existing item or add a new item by directly referencing its key Dictionary_object[“key”] = value. This will update the value if key is available else add new item into the dictionary.

Delete

You can delete a particular value based on its key or delete a key or delete dictionary object from namespace using built-in “del” keyword.

Delete Value
Delete Value

Dictonary Methods

You can use built-in “dir()” function to look up the available methods and attributes for the dictionary object.

Check Available Methods
Check Available Methods

clear() – This method will remove all the items from the dictionary object. This method does not take any argument.

Remove Items in Dictionary Object
Remove Items in Dictionary Object

Copy() – It will return a shallow copy of a dictionary object. The copy() method doesn’t take any parameters as an argument.

Copy of Dictionary Object
Copy of Dictionary Object

Keys() – This method returns view object for keys available in the dictionary as dictionary key object. This method does not take any argument.

Key Method
Key Method

Values() – This method returns a view object for values from the dictionary object. This method takes no argument.

Values Method
Values Method

Items() – This method returns a tuple(key,value) pair from the dictionary object.

Items Method
Items Method

Setdefault() – This method searches of a given key in a dictionary. If the key is not found in the dictionary then it will be added into the dictionary.
It takes 2 arguments dic.setdefault(key,[,default value]).

The default value is set to None if no value is specified.

Setdefault Method
Setdefault Method

get() – This method returns the value of the specified key if the key is available in a dictionary.

Syntax dict.get(key[, value]) 

This method takes 2 arguments. First is the input argument that will search for the given key in the dictionary and return the value of the key is found. The second argument will return the value if a key is not found. The default return value is set to “None”.

Get Method
Get Method

Update() – Update method add items to the dictionary if the key is not in the dictionary. If the key is found that key is updated with the new value. Update method accepts either another dictionary object of k: v pair or iterable object of k: v pair like pair of tuples.

Update Method
Update Method

Removing / Deleting Dictionary Object

Pop() – This method removes the value based on the key as input and returns the removed value.

This method accepts two parameters.

  1. Key – The key to be searched in the dictionary object.
  2. Default – Return value to be specified if the key is not found in the dictionary.

NOTE If key is not found in the dictionary and if you fail to specify the default value then “KeyError” will be raised.

Pop Method
Pop Method

Popitem() – Removes an arbitrary elements from the dictionary object. No argument is accepted and it returns “KeyError” if the dictionary is said to be empty.

Popitem Method
Popitem Method

Like list and tuples, we can use a del keyword to remove the items in the dictionary object or remove the dictionary object from the namespace.

Del Keyword
Del Keyword
Summary

In this article you have seen what is dictionary and how it differs from other data structures in python. You have also seen how to create, access, modify and delete dictionary objects.

The optimal use case of the dictionary is when we have to store the data based on a name and refer them by its name. In the next article, we will see another type of python built-in data structure “set/Frozenset”. Till then you can read more about dictionaries here.

Hey TecMint readers,

Exciting news! Every month, our top blog commenters will have the chance to win fantastic rewards, like free Linux eBooks such as RHCE, RHCSA, LFCS, Learn Linux, and Awk, each worth $20!

Learn more about the contest and stand a chance to win by sharing your thoughts below!

Karthick
A passionate software engineer who loves to explore new technologies. He is a public speaker and loves writing about technology, especially about Linux and open source.

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.