Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python Dictionary: Introduction

Python Dictionary - Complete Guide

Learn what dictionaries are in Python, how to create them, and their key characteristics.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Introduction to Dictionaries
  • Creating Dictionaries
  • Key Characteristics
  • Dictionary vs List
  • Practical Use Cases
  • Common Mistakes
  • Interactive Editor
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You Will Learn
  • What is a dictionary — definition and characteristics
  • Creating dictionaries — syntax and different ways
  • Key-value pairs — understanding keys and values
  • Dictionary vs List — key differences and when to use each
  • Use cases — practical applications of dictionaries

Introduction to Dictionaries

A dictionary is an unordered, mutable collection of key-value pairs in Python. Dictionaries are defined using curly braces {} and store data in a structure that maps unique keys to values.

The key characteristics of dictionaries are:

  • Key-value pairs — each element consists of a key and a value
  • Unique keys — keys must be unique within a dictionary
  • Mutable — can add, remove, and modify key-value pairs
  • Unordered — insertion order is not guaranteed (Python 3.7+ preserves insertion order)
  • Hashable keys — keys must be immutable (strings, numbers, tuples)

💡 Key concept: Dictionaries are ideal for storing data that needs to be accessed by a unique identifier (key), rather than by position (index).

Creating Dictionaries

1

Dictionary Creation Methods

Dictionaries can be created using curly braces {}, the dict() constructor, or using the dict.fromkeys() method.

# Using curly braces (most common)
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'NYC'}

# Using the dict() constructor
person = dict(name="Bob", age=30, city="LA")
print(person)  # {'name': 'Bob', 'age': 30, 'city': 'LA'}

# Empty dictionary
empty = {}
print(empty)  # {}

# From a list of tuples
items = [("name", "Charlie"), ("age", 35)]
person = dict(items)
print(person)  # {'name': 'Charlie', 'age': 35}

# Using dict.fromkeys() (creates dictionary with default values)
keys = ["name", "age", "city"]
person = dict.fromkeys(keys)
print(person)  # {'name': None, 'age': None, 'city': None}

# With a default value
person = dict.fromkeys(keys, "unknown")
print(person)  # {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}

Important notes:

  • Use {} for non-empty dictionaries with key-value pairs
  • Use dict() for creating from other structures
  • Keys must be hashable (immutable types)
  • Values can be any data type

Quick Check: What is the correct way to create an empty dictionary? (Answer: {} — set() creates an empty set)

Key Characteristics

2

Understanding Dictionary Properties

Dictionaries have several unique properties that distinguish them from other data structures.

# 1. Key-value pairs
person = {"name": "Alice", "age": 25}
print(person["name"])  # Alice
print(person["age"])   # 25

# 2. Unique keys (duplicate keys overwrite)
person = {"name": "Alice", "name": "Bob"}
print(person)  # {'name': 'Bob'} — last value wins

# 3. Mutable (can be modified)
person = {"name": "Alice", "age": 25}
person["age"] = 26  # Update
person["city"] = "NYC"  # Add new
print(person)  # {'name': 'Alice', 'age': 26, 'city': 'NYC'}

# 4. Unordered (Python 3.6+ preserves insertion order)
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(person)  # Insertion order is maintained in Python 3.7+

# 5. Keys must be hashable (immutable)
valid_dict = {1: "one", "two": 2, (1, 2): "tuple"}
# invalid_dict = {[1, 2]: "list"}  # TypeError: unhashable type: 'list'

Key properties:

  • Key-value pairs — each key maps to a value
  • Unique keys — keys must be unique
  • Mutable — can add, remove, and update
  • Hashable keys — keys must be immutable
  • Insertion order — Python 3.7+ preserves order

Quick Check: Can a list be used as a dictionary key? (Answer: No — lists are mutable and unhashable)

Dictionary vs List

3

Key Differences

Understanding the differences between dictionaries and lists helps you choose the right data structure for your needs.

# Comparison of dictionary and list

# 1. Access method
my_list = [10, 20, 30, 40, 50]
my_dict = {"a": 10, "b": 20, "c": 30}

print(my_list[0])   # 10 — access by index
print(my_dict["a"]) # 10 — access by key

# 2. Performance (lookup speed)
import time
large_list = list(range(1000000))
large_dict = {i: i for i in range(1000000)}

start = time.time()
999999 in large_list
print(f"List membership: {time.time() - start:.6f}s")

start = time.time()
999999 in large_dict
print(f"Dict membership: {time.time() - start:.6f}s")

# 3. Ordering
my_list = [1, 2, 3]  # Order is guaranteed
my_dict = {"a": 1, "b": 2, "c": 3}  # Order preserved in Python 3.7+

# 4. Mutability
my_list = [1, 2, 3]
my_dict = {"a": 1, "b": 2}
my_list[0] = 10  # Works
my_dict["a"] = 10  # Works

When to use each:

  • Use dictionaries when:
    • You need to access elements by a unique key
    • Fast lookup by key is important
    • You have key-value pairs data
    • Order doesn't matter (or Python 3.7+ order is sufficient)
  • Use lists when:
    • Order matters
    • You need index-based access
    • You have a sequence of items
    • You need to perform operations on all items

Practical Use Cases

4

Real-World Applications

Dictionaries are used in many practical scenarios in Python programming.

# 1. Storing user data
user = {
    "id": 1001,
    "name": "Alice Smith",
    "email": "alice@example.com",
    "active": True
}
print(f"User: {user['name']}")

# 2. Configuration settings
config = {
    "host": "localhost",
    "port": 8080,
    "debug": True,
    "timeout": 30
}
print(f"Server running on {config['host']}:{config['port']}")

# 3. Counting occurrences
text = "the cat in the hat with the cat and the hat"
words = text.split()
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1
print(word_count)

# 4. Mapping IDs to objects
employees = {
    101: {"name": "Alice", "department": "Engineering"},
    102: {"name": "Bob", "department": "Marketing"},
    103: {"name": "Charlie", "department": "Sales"}
}
print(employees[101]["name"])

# 5. Lookup tables
color_codes = {
    "red": "#FF0000",
    "green": "#00FF00",
    "blue": "#0000FF"
}
print(color_codes["green"])  # #00FF00

Common Mistakes

5

Pitfalls and Solutions

Mistake 1: Using a Mutable Key

# WRONG — raises TypeError
my_dict = {}
# my_dict[[1, 2]] = "value"  # TypeError: unhashable type: 'list'

# CORRECT — use immutable types
my_dict[(1, 2)] = "value"  # Tuple is hashable

Mistake 2: Accessing a Non-Existent Key

# WRONG — raises KeyError
person = {"name": "Alice", "age": 25}
# print(person["city"])  # KeyError: 'city'

# CORRECT — use get() method
city = person.get("city", "Unknown")
print(city)  # Unknown

Mistake 3: Assuming Dictionary Order

# WRONG — order is not guaranteed in older Python versions
my_dict = {"a": 1, "b": 2, "c": 3}
# Order is preserved in Python 3.7+ but not guaranteed in earlier versions

# CORRECT — use OrderedDict if order matters
from collections import OrderedDict
ordered = OrderedDict([("a", 1), ("b", 2), ("c", 3)])

Quick Check: What is the most common mistake with dictionaries? (Answer: Using mutable objects as keys — raises TypeError)

Interactive Editor

Experiment with dictionaries in the interactive editor below. Modify the code and observe the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
DICTIONARY PRACTICE
========================================

1. CREATING DICTIONARIES
Person: {'name': 'Alice', 'age': 25, 'city': 'NYC'}

2. ACCESSING VALUES
Name: Alice
Age: 25

3. ADDING AND UPDATING
Updated: {'name': 'Alice', 'age': 26, 'city': 'NYC', 'email': 'alice@example.com'}

4. DICTIONARY OPERATIONS
Keys: ['name', 'age', 'city', 'email']
Values: ['Alice', 26, 'NYC', 'alice@example.com']
Items: [('name', 'Alice'), ('age', 26), ('city', 'NYC'), ('email', 'alice@example.com')]

5. WORD COUNT EXAMPLE
Word count: {'the': 3, 'cat': 2, 'in': 1, 'hat': 2, 'with': 1, 'and': 1}

Dictionary practice complete!
🏆

Certificate of Completion

You have completed the Python Dictionary tutorial. You now understand dictionary creation, key-value pairs, characteristics, and the key differences between dictionaries and lists.

Quick Quiz — Test Your Knowledge

Let's see what you've learned about dictionaries:

1. What is the correct way to create an empty dictionary?
2. Which of the following is true about dictionary keys?
3. What happens when you use a duplicate key in a dictionary?
4. Which method safely retrieves a value without raising an error if the key doesn't exist?
5. Can a list be used as a dictionary key?

Frequently Asked Questions

What is a dictionary in Python? ▼

A dictionary is an unordered, mutable collection of key-value pairs in Python. Dictionaries are defined using curly braces {} and store data that can be accessed by a unique key.

What is the difference between a dictionary and a list? ▼

Dictionaries store key-value pairs and access elements by key. Lists store elements in order and access by index. Dictionaries provide faster lookup by key and are more suitable for mapping data.

Can a dictionary have duplicate keys? ▼

No, dictionary keys must be unique. If you assign a value to an existing key, the old value is overwritten.

What types can be used as dictionary keys? ▼

Dictionary keys must be immutable (hashable) types: strings, numbers, tuples, and frozensets. Lists, dictionaries, and sets cannot be used as keys.

Are dictionaries ordered in Python? ▼

In Python 3.7 and later, dictionaries preserve insertion order. In earlier versions, order was not guaranteed. If order matters in older Python versions, use OrderedDict.

How do I safely access a dictionary value without raising an error? ▼

Use the get() method: dict.get(key, default_value). This returns the value if the key exists, otherwise returns the default value (or None).

Where to Go From Here

After mastering dictionaries, consider exploring these related topics:

Access Dictionary Items

Learn how to access, add, and update dictionary items.

Learn More →

Dictionary Methods

Explore built-in dictionary methods and operations.

Learn More →

List vs Dictionary

Detailed comparison of lists and dictionaries.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Top PL SQL Interview Questions
Previous: Set Assignments Next: Access Dictionary Items →