Python Dictionaries – A Complete Guide for Beginners (with Examples and Output)

 

Dictionaries – A Complete Guide for Beginners (with Examples and Output)

Published on Code with Py  |  Category: Python Basics  |  Reading time: ~15 min

You have already learned about ListsTuples, and Sets. Now it is time to learn about Dictionaries — the most powerful and widely used data structure in Python. Unlike lists where you access items by their position, a dictionary lets you access items by a meaningful key. Think of it like a real dictionary — you look up a word (key) to find its meaning (value). In this complete guide, you will learn everything about Python dictionaries with simple examples, clear outputs, and real-life programs.

Table of Contents

  1. What is a Dictionary in Python?
  2. How to Create a Dictionary
  3. Accessing Dictionary Values
  4. Adding and Updating Items
  5. Removing Items from a Dictionary
  6. Important Dictionary Methods
  7. Looping Through a Dictionary
  8. Nested Dictionaries
  9. Dictionary Comprehension
  10. Checking Keys and Values
  11. All Data Structures Compared
  12. Real-Life Projects
  13. Practice Problems
  14. FAQ

1. What is a Dictionary in Python?

dictionary is a collection that stores data as key-value pairs. Instead of accessing items by their index number like in a list, you access them using a meaningful key that you define.

Think of a real English dictionary — you search for a word (the key) and it gives you the meaning (the value). In Python, a dictionary works exactly the same way.

"name""Rohan"
"age"21
"city""Bengaluru"
"marks"85.5

Dictionary properties

Key-value pairs — every item has a key and a value
Ordered — insertion order is preserved (Python 3.7+)
Mutable — you can add, change, or remove items
Keys must be unique — no duplicate keys allowed

When to use a dictionary

When data has labels (name, age, marks)
When you need fast lookup by a name or ID
When storing structured records like a student profile
When building configs, JSON data, or API responses


2. How to Create a Dictionary

A dictionary is created using curly brackets { } with key-value pairs separated by colons :. Each pair is separated by a comma.

# Basic dictionary
student = {
    "name"  : "Rohan",
    "age"   : 21,
    "city"  : "Bengaluru",
    "marks" : 85.5
}

print(student)
print(type(student))
print(len(student))   # Number of key-value pairs
{'name': 'Rohan', 'age': 21, 'city': 'Bengaluru', 'marks': 85.5}
<class 'dict'>
4

Creating a dictionary using dict()

# Using the dict() constructor
student = dict(name="Priya", age=20, city="Mumbai")
print(student)
{'name': 'Priya', 'age': 20, 'city': 'Mumbai'}

Empty dictionary

empty_dict = {}
print(empty_dict)
print(type(empty_dict))
{}
<class 'dict'>
Keys in a dictionary can be strings, integers, floats, or tuples — any immutable type. Values can be anything — strings, numbers, lists, even another dictionary.

3. Accessing Dictionary Values

You access values in a dictionary using the key inside square brackets [ ] or using the get() method. Unlike lists, you never use a number index — you use the key name.

student = {"name": "Rohan", "age": 21, "marks": 85}

# Access using key in [ ]
print(student["name"])
print(student["age"])

# Access using get() – safer method
print(student.get("marks"))
print(student.get("grade"))          # Key not found → None
print(student.get("grade", "N/A"))   # Key not found → "N/A"
Rohan
21
85
None
N/A
Using student["grade"] when "grade" does not exist raises a KeyError. Using student.get("grade") safely returns None instead. Always use get() when you are not sure if the key exists.

4. Adding and Updating Items

Since dictionaries are mutable, you can add new key-value pairs or update existing ones at any time. Both operations use the same syntax — just assign a value to a key.

Adding a new key-value pair

student = {"name": "Rohan", "age": 21}
print("Before:", student)

# Add new keys
student["city"]   = "Bengaluru"
student["marks"]  = 90
print("After:", student)
Before: {'name': 'Rohan', 'age': 21}
After:  {'name': 'Rohan', 'age': 21, 'city': 'Bengaluru', 'marks': 90}

Updating an existing value

student = {"name": "Rohan", "age": 21, "marks": 85}

student["marks"] = 92   # Update existing key
print(student)
{'name': 'Rohan', 'age': 21, 'marks': 92}

update() method — add or update multiple keys at once

student = {"name": "Rohan", "age": 21}

student.update({"city": "Bengaluru", "marks": 88, "age": 22})
print(student)
{'name': 'Rohan', 'age': 22, 'city': 'Bengaluru', 'marks': 88}
update() adds new keys if they don't exist, and updates existing keys if they do. It is the cleanest way to merge new data into an existing dictionary.

5. Removing Items from a Dictionary

student = {"name": "Rohan", "age": 21, "city": "Bengaluru", "marks": 85}

# pop() – removes by key and returns value
removed = student.pop("city")
print(f"Removed: {removed}")
print(student)

# popitem() – removes and returns the last inserted pair
last = student.popitem()
print(f"Last item removed: {last}")
print(student)

# del – deletes a key directly
del student["age"]
print(student)

# clear() – removes everything
student.clear()
print(student)
Removed: Bengaluru
{'name': 'Rohan', 'age': 21, 'marks': 85}
Last item removed: ('marks', 85)
{'name': 'Rohan', 'age': 21}
{'name': 'Rohan'}
{}
Use pop(key) when you know the key. Use popitem() to remove the last inserted item. Use del for a direct quick delete. Use clear() to wipe the entire dictionary.

6. Important Dictionary Methods

MethodWhat it doesReturns
keys()Returns all keysdict_keys view
values()Returns all valuesdict_values view
items()Returns all key-value pairs as tuplesdict_items view
get(key, default)Returns value for key, or default if not foundvalue or None
update(dict2)Adds or updates with another dictionaryNone
pop(key)Removes key and returns its valuevalue
popitem()Removes and returns the last key-value pair(key, value) tuple
clear()Removes all itemsNone
copy()Returns a shallow copy of the dictionarynew dict
setdefault(key, val)Returns value if key exists, else inserts key with valvalue

keys(), values(), and items()

student = {"name": "Rohan", "age": 21, "marks": 85}

print(student.keys())    # All keys
print(student.values())  # All values
print(student.items())   # All pairs

# Convert to list for easier use
print(list(student.keys()))
dict_keys(['name', 'age', 'marks'])
dict_values(['Rohan', 21, 85])
dict_items([('name', 'Rohan'), ('age', 21), ('marks', 85)])
['name', 'age', 'marks']

7. Looping Through a Dictionary

You can use a for loop to iterate through a dictionary. You can loop through keys, values, or both at the same time.

Loop through keys (default)

student = {"name": "Rohan", "age": 21, "marks": 85}

for key in student:
    print(key)
name
age
marks

Loop through values

for value in student.values():
    print(value)
Rohan
21
85

Loop through key-value pairs using items()

for key, value in student.items():
    print(f"{key}: {value}")
name: Rohan
age: 21
marks: 85
Always use .items() when you need both the key and value together in a loop. This is the most common way to loop through a dictionary in real Python programs.

8. Nested Dictionaries

nested dictionary is a dictionary inside another dictionary. This is very useful for storing complex, structured data — like a class full of students or a product catalogue.

classroom = {
    "student1": {"name": "Rohan",  "marks": 85, "grade": "B"},
    "student2": {"name": "Priya",  "marks": 92, "grade": "A"},
    "student3": {"name": "Arjun",  "marks": 67, "grade": "C"}
}

# Access nested values
print(classroom["student1"])
print(classroom["student2"]["name"])
print(classroom["student3"]["marks"])
{'name': 'Rohan', 'marks': 85, 'grade': 'B'}
Priya
67
# Loop through nested dictionary
print(f"{'Name':10} {'Marks':6} {'Grade'}")
print("-" * 26)
for sid, info in classroom.items():
    print(f"{info['name']:10} {info['marks']:6} {info['grade']}")
Name       Marks  Grade
--------------------------
Rohan         85  B
Priya         92  A
Arjun         67  C

9. Dictionary Comprehension

Just like list comprehension, Python allows dictionary comprehension — a short, clean way to create a dictionary from an existing sequence in a single line.

# Create a dict of squares
squares = {x: x**2 for x in range(1, 6)}
print(squares)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Create dict from two lists using zip()
names  = ["Rohan", "Priya", "Arjun"]
marks  = [85, 92, 67]

result = {name: mark for name, mark in zip(names, marks)}
print(result)
{'Rohan': 85, 'Priya': 92, 'Arjun': 67}
# Filter only passing marks using comprehension
all_marks = {"Rohan": 85, "Priya": 32, "Arjun": 67, "Meera": 24}

passing = {name: m for name, m in all_marks.items() if m >= 40}
print("Passed:", passing)
Passed: {'Rohan': 85, 'Arjun': 67}
Dictionary comprehension follows this pattern: {key: value for item in iterable if condition}. The if condition part is optional — use it when you need to filter items.

10. Checking Keys and Values

Use the in membership operator to check if a key or value exists in a dictionary.

student = {"name": "Rohan", "age": 21, "marks": 85}

# Check keys
print("name" in student)        # True
print("grade" in student)       # False
print("age" not in student)     # False

# Check values
print(85 in student.values())    # True
print("Rohan" in student.values()) # True
True
False
False
True
True

11. All Data Structures Compared

You have now learned all four major Python data structures — liststuplessets, and dictionaries. Here is a complete side-by-side comparison.

FeatureList [ ]Tuple ( )Set { }Dictionary { }
StoresValuesValuesUnique valuesKey-value pairs
Ordered?YesYesNoYes (3.7+)
Mutable?YesNoYesYes
Duplicates?YesYesNoKeys: No, Values: Yes
Access byIndexIndexLoop / inKey
Brackets[ ]( ){ }{ key: value }
Best used forOrdered changeable dataFixed protected dataUnique valuesLabelled structured data

12. Real-Life Projects

Project 1 – Student Report Card

students = {
    "Rohan": [85, 90, 78],
    "Priya": [92, 88, 95],
    "Arjun": [60, 55, 70]
}

print(f"{'Name':10} {'Average':8} {'Result'}")
print("-" * 30)

for name, marks in students.items():
    avg = sum(marks) / len(marks)
    result = "Pass" if avg >= 40 else "Fail"
    print(f"{name:10} {avg:7.1f}  {result}")
Name       Average  Result
------------------------------
Rohan         84.3  Pass
Priya         91.7  Pass
Arjun         61.7  Pass

Project 2 – Word Frequency Counter

sentence = "python is great python is easy python is fun"
words = sentence.split()

frequency = {}
for word in words:
    frequency[word] = frequency.get(word, 0) + 1

print("Word Frequencies:")
for word, count in frequency.items():
    print(f"  {word:10}: {count}")
Word Frequencies:
  python    : 3
  is        : 3
  great     : 1
  easy      : 1
  fun       : 1

Project 3 – Simple Contact Book

contacts = {
    "Rohan"  : "9876543210",
    "Priya"  : "9123456789",
    "Arjun"  : "9988776655"
}

name = input("Search contact: ")

if name in contacts:
    print(f"Phone: {contacts[name]}")
else:
    print("Contact not found.")
Search contact: Priya
Phone: 9123456789

13. Practice Problems

Try solving each problem on your own. Use what you have learned in this post and from the Python ListsPython Loops, and Python Operators posts.

Basic operations

  1. Create a student dictionary with 4 keys
  2. Access a value using a key
  3. Add a new key-value pair
  4. Update an existing value
  5. Delete a key using del

Methods practice

  1. Print all keys of a dictionary
  2. Print all values of a dictionary
  3. Loop through items() and print pairs
  4. Use get() with a default value
  5. Use setdefault() to add a missing key

Comprehension

  1. Create a dict of cubes from 1 to 5
  2. Pair two lists into a dictionary
  3. Filter only students with marks above 50
  4. Create a dict of word lengths
  5. Invert a dictionary (swap keys and values)

Real-life challenges

  1. Build a word frequency counter
  2. Create a mini phone book
  3. Store and display a student report card
  4. Count each character in a string
  5. Find the student with the highest marks
Post your solutions in the comments below — let's review them together and learn from each other!

Quick Summary – What You Learned
  • A dictionary stores data as key-value pairs using { key: value } syntax
  • Dictionaries are ordered (Python 3.7+), mutable, and keys must be unique
  • Access values using dict[key] or the safer dict.get(key)
  • Add or update items by assigning — dict[key] = value
  • Use pop(key) to remove by key, del dict[key] for direct delete
  • keys()values(), and items() give views of the dictionary
  • Use .items() with a for loop to get both key and value together
  • Nested dictionaries store structured data like records or profiles
  • Dictionary comprehension creates dictionaries in one clean line
  • Dictionaries are the foundation of JSON, APIs, and real-world Python programs

Frequently Asked Questions (FAQ)

Q1. What is the difference between a dictionary and a list in Python?

list stores items accessed by their numeric index (0, 1, 2...). A dictionary stores items accessed by meaningful keys that you define (like "name", "age", "marks"). Use a list when order matters. Use a dictionary when your data has labels.

Q2. Can a Python dictionary have duplicate keys?

No. Dictionary keys must be unique. If you assign the same key twice, the second assignment simply overwrites the first — the old value is replaced. Values, however, can be duplicated — multiple keys can hold the same value.

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

dict[key] raises a KeyError if the key does not exist. dict.get(key) returns None if the key is not found — no error is raised. You can also provide a default value: dict.get(key, "default"). Always prefer get() when the key might not exist.

Q4. Can dictionary values be a list or another dictionary?

Yes. Dictionary values can be any data type — strings, numbers, liststuplessets, or even another dictionary. This is what makes dictionaries so powerful for storing complex, structured data.

Q5. Are Python dictionaries ordered?

Yes — from Python 3.7 onwards, dictionaries maintain the insertion order of keys. This means items are always returned in the order you added them. In older versions of Python (3.6 and below), dictionaries were unordered.

Q6. What is dictionary comprehension and when should I use it?

Dictionary comprehension is a compact way to create a dictionary in a single line using the syntax {key: value for item in iterable}. Use it when you need to transform or filter data into a dictionary — it is cleaner and faster than using a traditional for loop to build a dictionary manually.


Found this post helpful? Share it with someone learning Python. Drop your practice solutions in the comments — happy to review them!

"A dictionary is not just a data structure — it is how Python thinks about the real world. Learn it well."

Comments

Popular posts from this blog

Python Strings – A Complete Guide for Beginners (with Examples)

Python Control Flow Statements – Complete Guide with Real-Life Examples

Python Loops Explained – for Loop and while Loop with Examples and Output