How to Deal with a Dictionary in Python with Examples?

Python Dictionary - Check this tutorial to explore the fundamentals and advanced features of handling dictionaries in Python. | ProjectPro

Dictionaries in Python are versatile data structures that efficiently store and retrieve key-value pairs. They are well-suited for counting the occurrences of items in a dataset or aggregating data based on some criteria. In data science and machine learning projects, dictionaries can tally frequency distributions of words, summarize categorical variables, or group data for analysis. This Python dictionary tutorial will cover various aspects of using dictionaries, from creation to manipulation. So, let's get started! 

What is a Dictionary in Python? 

A dictionary in Python is an unordered collection of items where each item consists of a key-value pair. Unlike lists or tuples, dictionaries use keys for indexing, allowing for fast and efficient data retrieval. They are defined using curly braces {}, and a colon separates each key-value pair. 

How to Create a Dictionary in Python? 

You can easily create a dictionary using curly braces {} and defining key-value pairs. Check the examples below - 

Alternatively, you can also create a dictionary with initial key-value pairs directly. Check the example below - 

How to Create a Dictionary from a String in Python? 

Python has several methods to create a dictionary from a string. You can parse the string and extract key-value pairs. One common approach is to split the string based on a delimiter and then iterate through the resulting substrings to form the dictionary. 

Check out the example below - 

The input_string contains key-value pairs separated by commas (,), with each pair consisting of a key and a value separated by a colon (:). The split method is used to break the string into individual pairs, and then another split operation is performed to separate the keys and values. The resulting key-value pairs are added to the dictionary.

How to Loop Through a Dictionary in Python? 

You can use a for loop to iterate over its keys, values, or key-value pairs to loop through a dictionary in Python. For example - 

Here, for key in my_dict iterates over the keys, for value in my_dict.values() iterates over the values, and for key, value in my_dict.items() iterates over key-value pairs. 

How to Access a Dictionary in Python? 

Accessing a dictionary in Python can be achieved through keys or values. Using a key, you can retrieve the corresponding value from the dictionary. Alternatively, you can search for a specific value and obtain its associated key. Python provides flexibility in accessing dictionary elements, allowing developers to choose the best method suits their needs. Examples of accessing a dictionary in Python are illustrated below. 

Example 1 - How to Find Key from Value in a Python Dictionary? 

You can iterate through the dictionary items and check for the desired value to find a key from a value in a Python dictionary. You can create a list of keys matching the specified value using list comprehension. This list can then retrieve the corresponding key or keys associated with the given value. 

Check the example below demonstrating how to find a key from a value in a Python dictionary:- 

Example 2 - How to Find Value from Key in a Python Dictionary? 

To find a value from a key in a Python dictionary, simply access the dictionary using the key. The key serves as an identifier, allowing direct retrieval of the associated value. Below is an example demonstrating how to find a value from a key in a Python dictionary:- 

How to Change a Key in a Dictionary Using Python? 

You can use the assignment operator (=) to change a key in a dictionary and update the value associated with the existing key. For example:- 

How to Add New Key Value Pair in Dictionary Using Python? 

You can use the assignment operator (=) to add a new key-value pair to a dictionary with the new key and its associated value. For Example:-

How to Save a Dictionary as CSV in Python? 

You need to use the csv module to save a dictionary as a CSV in Python. First, import the module. Next, open a file in write mode using csv.writer. Write the header using the writeheader() method and data with the writerow() method. Example:

This code saves the dictionary my_dict to a CSV file named 'output.csv' with the keys as headers and corresponding values in a row. Adjust filenames and paths as needed.  

How to Find the Highest Value in a Dictionary Using Python? 

You can use the max function with the key parameter to find the highest value in a Python dictionary. For example:- 

The max function identifies the key with the maximum value based on the dictionary's values using the key parameter. 

Dictionary vs List: What is the Difference Between List and Dictionary in Python? 

Lists and dictionaries are two distinct data structures, each serving different purposes. A list is an ordered collection of elements, allowing for indexing and iteration. Elements in a list are accessed using numerical indices, starting from zero. Lists are mutable, meaning you can modify their contents by adding, removing, or updating elements.

On the other hand, a dictionary is an unordered collection of key-value pairs. Instead of indices, dictionaries use keys for access. Keys must be unique, and they provide a way to retrieve corresponding values efficiently. Dictionaries are useful for scenarios where data association is crucial, as they provide a more intuitive and descriptive way to organize and retrieve information.

Aspect

List

Dictionary

Definition

Ordered collection of elements

Unordered collection of key-value pairs

Declaration Syntax

my_list = [item1, item2, item3]

my_dict = {key1: value1, key2: value2}

Accessing Elements

Accessed by index (e.g., my_list[0])

Accessed by key (e.g., my_dict['key'])

Mutability

Mutable (elements can be modified)

Mutable (values can be modified)

Length

Determined by len(my_list)

Determined by len(my_dict)

Element Duplication

Allowed

Keys must be unique, values can be duplicated

Memory Overhead

Lower compared to dictionaries

Higher compared to lists

Use Case

Suitable for ordered collections or sequences

Ideal for storing data with associated keys for quick lookup

How to Convert a Dictionary into a List in Python?

You can use the list() constructor to convert a dictionary into a list of its key-value pairs. For example - 

How to Convert Two Lists to a Dictionary in Python?

You can use the zip() function to combine two lists into a dictionary. For example - 

Example - How to Modify a Dictionary in Python?

Step 1 - Creating Dictionary

    unef_org = {"name" : "UNEF",

                "staff" : 32,

                "url" : "http://unef.org"}

    print(unef_org)

We have created a dictionary and printed it.

Step 2 - Changing the dictionary

We have changed the values by assigning new values to the features.   

    who_org = {}

    who_org["name"] = "WHO"

    who_org["staff"] = "10"

    who_org["url"] = "https://setscholars.com"

    print(who_org)    

Step 3 - Viewing few values

We created a new dictionary and printed the desired value by passing the value index. 

    unitas_org = {"name" : "UNITAS",

                  "staff" : 32,

                  "url" : ["https://setscholars.com",

                           "https://setscholars.info"]}

    print(unitas_org)

    print(unitas_org["url"])

    print(unitas_org["url"][0])

    print(unitas_org["url"][1]) 

So the output comes as

{"name": "UNEF", "staff": 32, "url": "http://unef.org"}

{"name": "WHO", "staff": "10", "url": "https://setscholars.com"}

{"name": "UNITAS", "staff": 32, "url": ["https://setscholars.com", "https://setscholars.info"]}

["https://setscholars.com", "https://setscholars.info"]

https://setscholars.com

https://setscholars.info

Get Your Hands on Python Operations Through ProjectPro! 

Understanding how to work with dictionaries in Python is a key skill for anyone learning to code. Getting hands-on experience through practical examples is crucial for mastering Python operations and problem-solving. This is where ProjectPro comes in. With over 270+ projects focused on data science and big data, ProjectPro is a fantastic resource for applying what you've learned in real-world situations. It's a simple yet powerful way to enhance your skills and make your learning journey more practical. So, jump into Python with ProjectPro – your go-to platform for hands-on learning. Build, experiment, and learn Python with useful skills. 

FAQs on Python Dictionary 

Python dictionaries are built on the foundation of a hash table data structure.

You can manipulate a Python dictionary by using various built-in methods, such as get(), update(), and pop() by accessing and modifying values using keys. Additionally, dictionary comprehension and iteration provide ways to manipulate and transform dictionary data.

Download Materials

What Users are saying..

profile image

Jingwei Li

Graduate Research assistance at Stony Brook University
linkedin profile url

ProjectPro is an awesome platform that helps me learn much hands-on industrial experience with a step-by-step walkthrough of projects. There are two primary paths to learn: Data Science and Big Data.... Read More

Relevant Projects

Stock Price Prediction Project using LSTM and RNN
Learn how to predict stock prices using RNN and LSTM models. Understand deep learning concepts and apply them to real-world financial data for accurate forecasting.

Deploy Transformer BART Model for Text summarization on GCP
Learn to Deploy a Machine Learning Model for the Abstractive Text Summarization on Google Cloud Platform (GCP)

Build Customer Propensity to Purchase Model in Python
In this machine learning project, you will learn to build a machine learning model to estimate customer propensity to purchase.

MLOps using Azure Devops to Deploy a Classification Model
In this MLOps Azure project, you will learn how to deploy a classification machine learning model to predict the customer's license status on Azure through scalable CI/CD ML pipelines.

PyTorch Project to Build a GAN Model on MNIST Dataset
In this deep learning project, you will learn how to build a GAN Model on MNIST Dataset for generating new images of handwritten digits.

NLP Project for Multi Class Text Classification using BERT Model
In this NLP Project, you will learn how to build a multi-class text classification model using using the pre-trained BERT model.

BERT Text Classification using DistilBERT and ALBERT Models
This Project Explains how to perform Text Classification using ALBERT and DistilBERT

AWS MLOps Project for ARCH and GARCH Time Series Models
Build and deploy ARCH and GARCH time series forecasting models in Python on AWS .

FEAST Feature Store Example for Scaling Machine Learning
FEAST Feature Store Example- Learn to use FEAST Feature Store to manage, store, and discover features for customer churn prediction machine learning project.

Build a Text Classification Model with Attention Mechanism NLP
In this NLP Project, you will learn to build a multi class text classification model with attention mechanism.