What is a Dictionary in Python with Examples

Introduction

If you ever needed to store data as pairs, like student names and their marks, Python dictionaries are your best friend. In this tutorial, you will learn what a dictionary is in Python, basic dictionary operations, and even how to convert a list to dictionary in Python through practical examples. It’s written for beginners and intermediate learners desiring clear explanations along with working code.

In Short

Data in a dictionary is stored in a key-value format; this leads to fast lookups and efficient methods of updating the data. This tutorial will cover how to create a dictionary, how to update and delete elements of a dictionary, some common looping techniques, some key differences between lists and dictionaries, and converting lists into dictionaries.

What is a Dictionary in Python

What is a Dictionary in Python?

In Python, a dictionary is the standard data type for storing information in key-value pairs. Each key must be unique and is utilized in the access to its related value.

Syntax

my_dict = {
    "name": "Ravi",
    "age": 22,
    "course": "Python"
}

Output:

{'name': 'Ravi', 'age': 22, 'course': 'Python'}

Note: The keys here (“name”, “age”, “course”) point to their matching values.

The dictionaries are enclosed in curly braces {}, and their values can be any data type: string, number, list, and even another dictionary.

Creating a Dictionary Program in Python

Now let’s write a simple dictionary program in Python for managing student details.

# dictionary program in python
students = {
    "John": 89,
    "Asha": 95,
    "Raj": 76
}

print("Student Marks:")
for name, marks in students.items():
    print(f"{name} scored {marks}")

Output:

Student Marks:
John scored 89
Asha scored 95
Raj scored 76

What this does: It creates a dictionary and loops through it to print each student’s name and marks.

Personal tip: For mapping entities, like usernames to user IDs or products to their prices, a dictionary is your go-to data structure.

Common Dictionary Operations in Python

Python are fast and easy. Let’s look at some common ones.

1.Accessing Values

person = {"name": "Neha", "city": "Pune"}
print(person["name"])

Output:

Neha

2. Adding or Updating Items

person["age"] = 25
person["city"] = "Mumbai"
print(person)

Output:

{'name': 'Neha', 'city': 'Mumbai', 'age': 25}

3. Removing Items

del person["city"]
print(person)

Output:

{'name': 'Neha', 'age': 25}

4. Looping Through Keys and Values

for key, value in person.items():
    print(key, ":", value)

Output:

name : Neha
age : 25

5. Checking Existence

print("age" in person)

Output:

True

Quick Note:
Dictionary operations are very fast in Python because, under the hood, dictionaries use a hashing mechanism.

Compare List and Dictionary in Python

Both lists and dictionaries are used to store data; however, they behave differently. Understanding their respective uses helps improve code efficiency.

FeatureListDictionary
Data structureOrdered collectionKey-value pair
Access methodBy indexBy key
Duplicates allowedYesKeys must be unique
Example[1, 2, 3]{'a': 1, 'b': 2}
Lookup speedSlower for large dataFaster (hash-based)
  • Use list when data is sequential.
  • Use dictionary when data needs to be referenced with unique identifiers – like names or IDs.

How to Convert List to Dictionary in Python

Sometimes you’ll have data in lists but want to organize it into key-value format.

Example: Pair two lists into a dictionary

# how to convert list to dictionary in python
keys = ["name", "age", "city"]
values = ["Ravi", 23, "Delhi"]

student = dict(zip(keys, values))
print(student)

Output:

{'name': 'Ravi', 'age': 23, 'city': 'Delhi'}

What this does:
zip() pairs up corresponding items from two lists, and dict() turns them into a dictionary. Example 2: Using List of Tuples

Example 2: Using List of Tuples

data = [("apple", 100), ("banana", 60), ("grapes", 120)]
price_dict = dict(data)
print(price_dict)

Output:

{'apple': 100, 'banana': 60, 'grapes': 120}

Personal Tip: This is useful when reading comma-separated value files where one column can be keys – such as product names – and another can be values such as prices.

Nested Dictionaries in Python

A dictionary can even contain another dictionary, enabling you to represent structured data in an easy way.

company = {
    "emp1": {"name": "Amit", "dept": "HR"},
    "emp2": {"name": "Sara", "dept": "IT"}
}
print(company["emp2"]["dept"])

Output:

IT

Use Case: Nested dictionaries are suitable to represent JSON-like data or configurations.

Practical Example: Counting Words Using Dictionary

Here’s a real example using Python dictionary operations for one such common problem – word frequency count:

# Count word frequency using dictionary
text = "python tutorial for python beginners"
word_count = {}

for word in text.split():
    word_count[word] = word_count.get(word, 0) + 1

print(word_count)

Output:

{'python': 2, 'tutorial': 1, 'for': 1, 'beginners': 1}

What this does: Each unique word becomes a key, and its count becomes the value — a common pattern in text analysis projects.

What is a Dictionary in Python

Advantages of Dictionaries

  • Fast lookups via hashing.
  • Easy data mapping.
  • Clear structure for real-world entities.
  • Flexible — can hold mixed data types.

Summary of Key Takeaways

  • A dictionary stores data as key-value pairs.
  • You can easily update, delete, and loop through dictionaries.
  • Dictionaries are faster than lists for lookups.
  • You can use either zip() or dict() to convert lists into dictionaries
  • Useful for structured data and JSON-like patterns.

FAQs About Python Dictionaries

1. What is a dictionary in Python?
A dictionary in programming is a datatype that stores data as key-value pairs, typically allowing for fast lookups and updates.

2. . How do dictionaries differ from lists?
Lists store data sequentially using indexes, while dictionaries use keys to allow fast lookups.

3. How do I add a new key-value pair?
Simply assign a new key: my_dict["new"] = "value".

4. Can dictionary keys be numbers or tuples?
Yes, if they are immutable types. Immutable types include strings, numbers, and tuples.

5. How to Convert List to Dictionary in Python?
Use dict(zip(list1, list2)) if you have matching keys and values.

if you want to learn more about the dictionary then check Dictionary

For more Topics

related topics:

Recursion in Python: Beginner’s Friendly Guide with Examples
Learn Factorial and Fibonacci Series
Named Tuple in Python: Simple Guide with Practical Examples
Is Tuple Mutable in Python? In-depth Explanation
Difference Between List Tuple Set and Dictionary in Python
Tuple Methods in Python with Practical Examples
What is Tuple in Python with Example
What Is Set in Python | with Example  

Leave a Reply

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