Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Dictionaries in Python: A Complete Tutorial with Code Examples

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

Dictionaries in Python are essential data structures that allow for the storage and manipulation of data in key-value pairs. A range of numbers indexes lists, while keys index dictionaries. Which can be any immutable type. This makes dictionaries incredibly powerful and flexible for various programming tasks.

 

In this tutorial, we will explore the various aspects of dictionaries in Python, from their characteristics and creation to accessing and updating built-in functions and methods. After reading this article, you will understand how to effectively use dictionaries in your Python programs.

What is a Dictionary in Python?

In Python, a dictionary is a mutable, unordered collection of items where each item is stored in a key-value pair. Dictionaries are commonly used to store data in a way that allows quick access and modification. Here’s a brief overview of dictionaries in Python language.

Characteristics of Python Dictionaries 

  • Key-Value Pairs: In the Dictionary, each item is a pair consisting of a key and a value. Keys must be unique and immutable(e.g., strings, numbers, or tuples), while values of any data type can be duplicated.

 

  • Unordered: Python dictionaries are unordered collections, which means that items do not have a defined order and cannot be accessed by an index.

 

  • Mutable: Dictionaries are mutable, meaning you can add, remove or change items after creating the dictionary.

Creating a Dictionary

Creating a Python dictionary is very simple. The required key and value pairs are within curly brackets and separated by the key-value pair.

 

The following program creates a dictionary in Python language.

 

Program

# Using curly braces my_dict = {     "name": "Rahul",     "age": 23,     "city": "Delhi" } my_dict2 = dict(name="Alice", age=25, city="New York") print(my_dict) print(my_dict2)

Output

{'name': 'Rahul', 'age': 23, 'city': 'Delhi'} {'name': 'Alice', 'age': 25, 'city': 'New York'}

 

Program

empty_dict = {} print(empty_dict)  # Output: {}

Output

{}

Accessing values in Python Dictionary

In Python, we can access the dictionary items using the square brackets that are also commonly used for indexing and slicing strings in Python).

 

The following program access time from the dictionary in Python language

 

Program

# Using curly braces my_dict = { "name": "Voldemort", "age": 21, "city": "Metro" } my_dict2 = dict(name="RajKumar", age=25, city="Washington DC") print(my_dict['name']) print(my_dict2['city'])

 

Output

Voldemort Washington DC

 

Updating Dictionary in Python

We can also update the dictionary in Python language in Python. We can add a new entry or modify the existing entry and add multiple values to a single key.

 

The following program demonstrates updating the dictionary values in Python.

 

Program

#creating an empty dictionary my_dict={} print(my_dict) #adding elements to the dictionary one at a time my_dict[1]="Voldemort" my_dict[2]="Harry" my_dict[3]="RajKumar" print(my_dict) #modifying existing entry my_dict[2]="Apple Laptop" print(my_dict) #adding multiple values to a single key my_dict[4]="Banana,Cherry,Kiwi" print(my_dict) #adding nested key values my_dict[5]={'Nested' :{'1' : 'Hero Vired', '2': 'Academy'}} print(my_dict)

Output

{} {1: 'Voldemort', 2: 'Harry', 3: 'RajKumar'} {1: 'Voldemort', 2: 'Apple Laptop', 3: 'RajKumar'} {1: 'Voldemort', 2: 'Apple Laptop', 3: 'RajKumar', 4: 'Banana,Cherry,Kiwi'} {1: 'Voldemort', 2: 'Apple Laptop', 3: 'RajKumar', 4: 'Banana,Cherry,Kiwi', 5: {'Nested': {'1': 'Hero Vired', '2': 'Academy'}}}
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Deleting Dictionary Elements

We can also delete the dictionaries in Python language. Let’s look at “ how we can either delete the dictionary entirely or remove individual entries”.

 

To remove an entire dictionary. We can use the ‘del’ keyword in Python language.

 

The following program demonstrates “del keyword in Python”.

 

Program

my_dict={1: 'Neeraj', 2: 'Laptop', 3: 'Computer', 4: 'Computer', 5 :"Raj Kumar"} del my_dict[4] print(my_dict)

Output

{1: 'Neeraj', 2: 'Laptop', 3: 'Computer', 5: 'Raj Kumar'}

We can also clear the whole dictionary using the clear()method.

my_dict={1: 'Neeraj', 2: 'Voldemort', 3: 'RajKumar', 4: 'Cherry Potter'} print(my_dict) my_dict.clear() print(my_dict)

Output

{1: 'Neeraj', 2: 'Voldemort', 3: 'RajKumar', 4: 'Cherry Potter'} {} Python Dictionary Comprehension

Iterating Dictionary in Python

You can iterate through a dictionary’s keys, values, or key-value pairs in Python language.

 

The following program Iterate the dictionary using the loop.

 

Program

# Iterating through keys my_dict = { "name": "Alice", "age": 25, "city": "New York" } for key in my_dict: print(key, my_dict[key]) # Iterating through values for value in my_dict.values(): print(value) # Iterating through key-value pairs for key, value in my_dict.items(): print(key, value)

Output

name Alice age 25 city New York Alice 25 New York name Alice age 25 city New York<strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;"> </strong>

Properties of Python Dictionary Keys

Let’s see the properties of Python dictionary kes summarized in single points.

 

  • Immutability: Python dictionary must be immutable.
  • Uniqueness: Python keys within a dictionary must be unique
  • Hashability: Python keys must be hashable.
  • Comparable: Python keys must support equality comparison

Built-in Python Dictionary Functions & Methods

There are some built-in methods and functions in Python.

 

Functions Description
cmp(dict1, dict2) This function compares the items of both dictionaries and returns true if the value of the first dictionary. Suppose the first value is greater than It will return true otherwise.  It will return false.
len(dict) It gives the total number of items in the dictionary
str(dict) This function produces a string representation of the dictionary
all(dict) This function returns true if all the keys in the dictionary are true.
any(dict) This function returns true if any key in the dictionary is true.
sorted(dict) It returns a new sorted list of keys in a dictionary
dict.clear() This method removes all elements from the dictionary.
dict.copy() This function returns a copy of the dictionary
dict.pop() This function removes an element from the specified key.
dict.get() This function is used to get the value of the specified  key
dict.fromkeys() This function creates a new dictionary with keys from seq and values set to value.
dict.items() This function returns the list of dictionary tuple pairs.
dict.update(dict2) This adds the dict2 key-value pairs to dict
dict.has_key() This function returns true if the specified key is present in the dictionary else false.

Conclusion

In this article, we learned about the dictionaries in Python. It is a versatile and powerful data structure tool that efficiently stores and manages data using key-value pairs. It offers several advantages, such as fast lookups, flexibility in data types for keys and values, and ease of use with various built-in methods. Mastering Python dictionaries enhances your capability to handle data efficiently, perform rapid searches, and develop sophisticated applications. There are also some built-in methods and functionalities, such as ‘get()’, ‘update()’, ‘items()’, ‘keys()’ and values()’.

 

FAQs
A dictionary in Python is an unordered collection of items. Each item is stored as a key-value pair where each key is unique and maps to a value.
Dictionary keys must be of a hashable type, typically including immutable type like strings, numbers, and tuples. Lists and other dictionaries cannot be used as keys.
The syntax of the python dictionary begins with left curly braces({), ends with the right curly brace(}), and contains zero or more key: value items separated by commas, (,). The key is separated from the value by a colon(:).
A dictionary can be created from two lists using the ‘zip()’ function. This function pairs elements from both lists and then converts them into key-value pairs.
Yes, A dictionary can have duplicate values but not duplicate keys.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

19 October, 12:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved