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: Access Items

Python Dictionary Access Items - Complete Guide

Learn how to access, add, and update dictionary items using keys, get method, and advanced techniques.

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 Dictionary Access
  • Key Indexing
  • Using get() Method
  • Adding Items
  • Updating Items
  • Deleting Items
  • Common Mistakes
  • Interactive Editor
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You Will Learn
  • Key indexing — accessing values using keys
  • get() method — safely retrieving values
  • Adding items — adding new key-value pairs
  • Updating items — modifying existing values
  • Deleting items — removing key-value pairs
  • Common mistakes — and how to avoid them

Introduction to Dictionary Access

Accessing items in a dictionary is a fundamental operation in Python. Unlike lists which use numeric indices, dictionaries use keys to access values. This makes dictionaries ideal for storing and retrieving data by a meaningful identifier.

The primary methods for accessing dictionary items are:

  • Key indexing — using dict[key] to retrieve values
  • get() method — safely retrieving values with a default
  • Adding items — assigning values to new keys
  • Updating items — modifying existing key-value pairs
  • Deleting items — removing key-value pairs

💡 Key concept: Dictionaries provide fast lookups by key (O(1) average time complexity), making them ideal for data retrieval operations.

Key Indexing

1

Accessing Values Using Keys

The most direct way to access a dictionary value is to use the key inside square brackets []. This is similar to list indexing but uses keys instead of positions.

# Basic key indexing
person = {"name": "Alice", "age": 25, "city": "NYC"}

print(person["name"])   # Alice
print(person["age"])    # 25
print(person["city"])   # NYC

# Accessing nested dictionary values
user = {
    "name": "Alice",
    "address": {
        "street": "123 Main St",
        "city": "NYC",
        "zip": "10001"
    }
}
print(user["address"]["city"])  # NYC

# Using variables as keys
key = "name"
print(person[key])  # Alice

# Working with different key types
data = {
    "string_key": "value1",
    42: "value2",
    (1, 2): "value3"
}
print(data["string_key"])  # value1
print(data[42])            # value2
print(data[(1, 2)])        # value3

Characteristics:

  • Uses dict[key] syntax
  • Raises KeyError if the key doesn't exist
  • Works with any hashable key type
  • Time complexity: O(1) on average

Quick Check: What happens when you try to access a non-existent key using dict[key]? (Answer: KeyError is raised)

Using get() Method

2

Safe Value Retrieval

The get() method provides a safe way to retrieve values from a dictionary. If the key doesn't exist, it returns a default value instead of raising an error.

# Basic get() usage
person = {"name": "Alice", "age": 25}

print(person.get("name"))   # Alice
print(person.get("city"))   # None (default)
print(person.get("city", "Unknown"))  # Unknown

# Working with different default values
config = {"host": "localhost", "port": 8080}
print(config.get("host", "127.0.0.1"))    # localhost
print(config.get("timeout", 30))          # 30

# Checking if a key exists
if person.get("city") is None:
    print("City not found")

# get() with nested dictionaries
user = {"name": "Alice", "address": {"city": "NYC"}}
city = user.get("address", {}).get("city", "Unknown")
print(city)  # NYC

# Practical use: counting with get()
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)  # {'apple': 3, 'banana': 2, 'cherry': 1}

Characteristics:

  • Returns the value if the key exists
  • Returns None or a default value if the key doesn't exist
  • No error is raised
  • Ideal for safe data retrieval

Quick Check: What does get() return if the key is not found? (Answer: None or the specified default value)

Adding Items

3

Adding New Key-Value Pairs

Adding items to a dictionary is done by assigning a value to a new key. If the key doesn't exist, it is created.

# Adding a new key-value pair
person = {"name": "Alice", "age": 25}
person["city"] = "NYC"
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'NYC'}

# Adding multiple items
person["email"] = "alice@example.com"
person["phone"] = "555-1234"
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234'}

# Adding with variable keys
key = "country"
person[key] = "USA"
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234', 'country': 'USA'}

# Adding to a nested dictionary
person["address"] = {}
person["address"]["street"] = "123 Main St"
person["address"]["zip"] = "10001"
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234', 'country': 'USA', 'address': {'street': '123 Main St', 'zip': '10001'}}

Characteristics:

  • New keys are added automatically
  • If the key already exists, the value is updated
  • Keys can be any hashable type
  • Values can be any data type

Quick Check: What happens when you assign a value to an existing key? (Answer: The existing value is updated)

Updating Items

4

Modifying Existing Values

Updating values in a dictionary is done by assigning a new value to an existing key. The update() method can also be used to update multiple items.

# Updating a single value
person = {"name": "Alice", "age": 25, "city": "NYC"}
person["age"] = 26
print(person)  # {'name': 'Alice', 'age': 26, 'city': 'NYC'}

# Using update() method
person.update({"city": "LA", "age": 27})
print(person)  # {'name': 'Alice', 'age': 27, 'city': 'LA'}

# Updating multiple values
person.update({"email": "alice@example.com", "phone": "555-1234"})
print(person)  # {'name': 'Alice', 'age': 27, 'city': 'LA', 'email': 'alice@example.com', 'phone': '555-1234'}

# Using update() with keyword arguments
person.update(age=28, city="SF")
print(person)  # {'name': 'Alice', 'age': 28, 'city': 'SF', 'email': 'alice@example.com', 'phone': '555-1234'}

# Using update() with a list of tuples
person.update([("age", 29), ("city", "NYC")])
print(person)  # {'name': 'Alice', 'age': 29, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234'}

Methods:

  • Direct assignment — dict[key] = new_value
  • update() — updates with another dictionary or iterable
  • Both methods modify the dictionary in place
  • If keys don't exist, they are added

Quick Check: What does update() do if the key doesn't exist? (Answer: It adds the new key-value pair)

Deleting Items

5

Removing Key-Value Pairs

Items can be removed from a dictionary using the del statement, pop() method, or popitem() method.

# Using del statement
person = {"name": "Alice", "age": 25, "city": "NYC", "email": "alice@example.com"}
del person["email"]
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'NYC'}

# Using pop() (removes and returns value)
person = {"name": "Alice", "age": 25, "city": "NYC"}
city = person.pop("city")
print(city)    # NYC
print(person)  # {'name': 'Alice', 'age': 25}

# pop() with default value
age = person.pop("age", 0)
print(age)     # 25
country = person.pop("country", "Unknown")
print(country) # Unknown

# Using popitem() (removes and returns last inserted item)
person = {"name": "Alice", "age": 25, "city": "NYC"}
item = person.popitem()
print(item)    # ('city', 'NYC')
print(person)  # {'name': 'Alice', 'age': 25}

# Using clear() (removes all items)
person.clear()
print(person)  # {}

Methods:

  • del dict[key] — removes the key-value pair
  • pop(key) — removes and returns the value
  • popitem() — removes and returns the last inserted item
  • clear() — removes all items

Quick Check: What is the difference between pop() and del? (Answer: pop() returns the removed value; del does not)

Common Mistakes

6

Watch Out For These!

Mistake 1: Accessing Non-Existent Keys

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

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

Mistake 2: Using Mutable Keys

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

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

Mistake 3: Forgetting that update() Modifies in Place

# WRONG — expecting a new dictionary
person = {"name": "Alice", "age": 25}
new_person = person.update({"city": "NYC"})  # Returns None
print(new_person)  # None

# CORRECT — update modifies in place
person.update({"city": "NYC"})
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'NYC'}

Quick Check: What is the most common mistake when accessing dictionary items? (Answer: Accessing a non-existent key without checking)

Interactive Editor

Experiment with accessing dictionary items directly in your browser. Modify the code and see the results in real time.

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

Original: {'name': 'Alice', 'age': 25, 'city': 'NYC'}

1. KEY INDEXING
Name: Alice
Age: 25

2. GET() METHOD
get('city'): NYC
get('country', 'USA'): USA

3. ADDING ITEMS
After adding: {'name': 'Alice', 'age': 25, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234'}

4. UPDATING ITEMS
After updating: {'name': 'Alice', 'age': 26, 'city': 'LA', 'email': 'alice@example.com', 'phone': '555-5678'}

5. DELETING ITEMS
Removed phone: 555-5678
After pop: {'name': 'Alice', 'age': 26, 'city': 'LA', 'email': 'alice@example.com'}
After del: {'name': 'Alice', 'age': 26, 'city': 'LA'}

6. GET() FOR COUNTING
Word counts: {'apple': 3, 'banana': 2, 'cherry': 1}

Dictionary access practice complete!
🏆

Certificate of Completion

You have completed the Python Dictionary Access Items tutorial. You understand key indexing, get() method, adding, updating, and deleting dictionary items.

Quick Quiz — Test Your Knowledge

Let's see what you've learned about accessing dictionary items:

1. How do you access a value in a dictionary using a key?
2. Which method safely retrieves a value without raising an error?
3. How do you add a new key-value pair to a dictionary?
4. Which method removes and returns the value for a given key?
5. What does dict.update() do if the key doesn't exist?

Frequently Asked Questions

What is the difference between dict[key] and dict.get(key)? ▼

dict[key] raises a KeyError if the key doesn't exist. dict.get(key) returns None or a default value if the key doesn't exist, without raising an error.

How do I add multiple items to a dictionary at once? ▼

Use the update() method: dict.update({"key1": value1, "key2": value2}) or dict.update([("key1", value1), ("key2", value2)]).

What is the difference between pop() and popitem()? ▼

pop(key) removes and returns the value for a specific key. popitem() removes and returns the last inserted key-value pair (or an arbitrary pair in older Python versions).

Can I use variables as dictionary keys? ▼

Yes, you can use variables as keys: key = "name"; value = dict[key]. The variable value is used as the key.

How do I check if a key exists in a dictionary? ▼

Use the in operator: if key in dict: or use dict.get(key) and check for None.

What does dict.update() return? ▼

dict.update() returns None. It modifies the dictionary in place.

Where to Go From Here

After mastering dictionary access, consider exploring these related topics:

Dictionary Methods

Explore all built-in dictionary methods and operations.

Learn More →

Iterate Dictionary

Learn different ways to loop through dictionaries.

Learn More →

Nested Dictionaries

Work with dictionaries within 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: Dictionary Next: Dictionary Methods →