Login Register

What Is a Python Dictionary?

What Is a Dictionary?

  • A Python dictionary is a essential data structure that uses key-value pairs mechanism to stores information inside it.
  • You can compare with a real dictionary, where you search for a word (key) and get the meaning (value).
  • Python uses the same idea in programming; you ask for a key, and Python returns its connected value.

Features of Python Dictionaries

1) Key-Value Style Storage

  • Each element is written like key: value
  • This allows you to store structured data clearly, similar to storing a student’s record, product info, settings, etc.

2) Mutable Structure

  • Mutable means we can add new items, update old items, or delete entries anytime without recreating the dictionary.

3) Unique and Immutable Keys

  • A dictionary has unique and immutable keys, which means you can’t have two keys with the same name.
  • If you try to add a duplicate value, Python will overwrite the previous value. For example:
data = {"name": "Riya", "name": "Amit"}
print(data)

# Output: {'name': 'Amit'}

4) Order Preserved (Python 3.7+)

  • Before Python 3.7, dictionaries did not guarantee that items stayed in the same order as you added them.
  • But from Python 3.7 onward, dictionaries started remembering the insertion order.
  • Whatever order you add in the key-value pairs, Python will keep that same order when you print or loop through the dictionary.

How to Create a Dictionary In Python?

Dictionary created by two methods, either curly braces { } or the dict () constructor, and both methods allow you to store data as key-value pairs.

Syntax of a Dictionary:

dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}
  • Always key should be unique, and the value can be anything (string, number, list, tuple, or even another dictionary).

Example 1: Creating a Dictionary Using Curly Braces

# Creating a dictionary of a library book record
book_record = {
"title": "The Silent River",
"author": "R. Mehta",
"pages": 220,
"is_available": True
}

print(book_record)

Example 2: Creating a Dictionary Using dict() Constructor

The dict() function allows you to build a dictionary using key=value style, but the key must be valid, which means no spaces or no special characters.

# Creating a dictionary of a travel ticket using dict()
ticket_info = dict(
passenger="Arjun Patel",
destination="Goa",
seat_no=14,
meal_preference="Vegetarian"
)

print(ticket_info)

This above code produces:

{'passenger': 'Arjun Patel', 'destination': 'Goa', 'seat_no': 14, 'meal_preference': 'Vegetarian'}

How To Access Dictionary Elements In Python?

Dictionary values are accessed using their keys, not indexes. We have two methods to access values:

  • Using square brackets [ ]
  • Using the get() method

Both methods retrieve values, but get() is safe because it doesn’t throw an error if the key doesn’t exist.

Example 1: Accessing Values Using Keys

# Dictionary storing details of a movie
movie_info = {
"title": "Sky Beyond",
"year": 2024,
"rating": 8.7
}

# Accessing values using keys
print(movie_info["title"]) # Output: Sky Beyond
print(movie_info["rating"]) # Output: 8.7
  • This uses direct key access; if a key doesn’t exist, Python will raise a KeyError.

Example 2: Accessing Values Using get() Method

# Dictionary of a student's progress report
progress = {
"name": "Riya Sharma",
"math": 92,
"science": 88
}

# Using get() to safely access values
print(progress.get("math")) # Output: 92
print(progress.get("science")) # Output: 88

Adding and Updating Dictionary Items

You can add new key-value pairs or update existing ones by assigning values to keys.

Adding a New Key-Value Pair

In this example, we create a dictionary that stores some basic details of a book, then we add a new key “stock”.

# Dictionary with initial book details
book = {
"title": "Hidden Waves",
"author": "Mira Patel"
}

# Adding a new key-value pair
book["stock"] = 12

print(book)

# Output: {'title': 'Hidden Waves', 'author': 'Mira Patel', 'stock': 12}

Explanation of the code:

  • A new entry “stock”: 12 is added because the key did not exist earlier.

Updating an Existing Item

Here we update the “author” name and change the “stock” value.

# Updating the existing key-value pairs
book["author"] = "Mira K. Patel" # author updated
book["stock"] = 20 # stock updated

print(book)


# Output: {'title': 'Hidden Waves', 'author': 'Mira K. Patel', 'stock': 20}
  • Since the keys already existed, Python replaced the old values with the new ones.

Example: Dynamic User Profile

# Creating a small user profile dictionary
profile = {
"username": "techLearner",
"points": 40
}

# Adding new information
profile["rank"] = "Beginner"

# Updating existing information
profile["points"] = profile["points"] + 10 # increasing points

print(profile)


# Output will the: {'username': 'techLearner', 'points': 50, 'rank': 'Beginner'}
  • Here, “rank” was newly added
  • “points” was updated by adding 10

Removing Items from a Dictionary

Python dictionaries provide multiple methods to delete data from a dictionary.

MethodDescription
pop(key)Removes the item with the specified key and returns its value.
popitem()Removes and returns the last key-value pair (insertion order maintained).
delDeletes an item or the entire dictionary.
clear()Removes all elements from the dictionary.

Removing an Item Using pop() Method

In this code example, we start with a dictionary that stores a gadget’s details, then we remove the “price” entry.

# Dictionary storing gadget information
gadget = {
"model": "XPad Mini",
"brand": "TechNova",
"price": 8999
}

# Removing a specific key using pop()
removed_price = gadget.pop("price")

print("Removed Value:", removed_price)
print("Updated Dictionary:", gadget)

# Expected Output:
# Removed Value: 8999
# Updated Dictionary: {'model': 'XPad Mini', 'brand': 'TechNova'}
  • pop(“price”) removes only that item and returns its value.

Removing the Last Inserted Item Using popitem()

# Dictionary with laptop details
laptop = {
"name": "SkyBook",
"battery": "48Wh",
"color": "Silver"
}

# popitem() removes the last inserted item
last_removed = laptop.popitem()

print("Removed Pair:", last_removed)
print("After Removal:", laptop)

Output:

Removed Pair: ('color', 'Silver')
After Removal: {'name': 'SkyBook', 'battery': '48Wh'}

Removing a Specific Item Using del

Here, we will remove “battery” field.

# Dictionary of a simple watch details
watch = {
"brand": "TimeOne",
"battery": "2 years",
"type": "Analog"
}

# Using del to remove a key-value pair
del watch["battery"]

print(watch)

# Expected Output:
# {'brand': 'TimeOne', 'type': 'Analog'}
  • del directly deletes the item without returning anything.

Removing All Items Using clear()

# Creating a dictionary with demo data
settings = {
"volume": 70,
"brightness": 50,
"wifi": True
}

# Clearing all items
settings.clear()

print(settings)

# Expected Output:
# {}

Output of empty dictionary:

{}

Dictionary Methods In Python

Dictionaries come with several built-in methods that make it easy to explore keys, values, pairs, and update or copy data.

These methods help us when we store dynamic or large datasets.

MethodDescription
keys()
Gives a list-like view of all keys in the dictionary.
values()Gives a view of all values.
items()Gives key-value pairs together.
update(other)Adds items from another dictionary or iterable.
copy()Creates a shallow copy of the dictionary.

1. Using keys() Method

This example shows the key of a device configuration dictionary.

# Dictionary storing basic device config
device_config = {
"mode": "silent",
"brightness": 60,
"bluetooth": False
}

# Getting all keys
print("Available Keys:", device_config.keys())

Output of this code:

Available Keys: dict_keys(['mode', 'brightness', 'bluetooth'])

2. Using values() Method

We retrieve only the values from a dictionary.

# Dictionary storing app settings
app_settings = {
"theme": "dark",
"font_size": 14,
"autosave": True
}

# Getting all values
print("Settings Values:", app_settings.values())

Output:

Settings Values: dict_values(['dark', 14, True])

3. Using items() Method

This logic prints both keys and values together.

# Dictionary that stores course information
course = {
"title": "Python Basics",
"duration": "4 weeks",
"fee": 199
}

# Getting key-value pairs
print("Course Details:", course.items())

Expected Output:

Course Details: dict_items([('title', 'Python Basics'), ('duration', '4 weeks'), ('fee', 199)])

4. Updating a Dictionary with update()

Now we will add new fields and update one value.

# Original dictionary of employee record
employee = {
"id": 501,
"name": "Karan",
"role": "Support"
}

# Updating with new information
employee.update({
"role": "Senior Support",
"location": "Mumbai"
})

print("Updated Record:", employee)

Output with updated fields:

Updated Record: {'id': 501, 'name': 'Karan', 'role': 'Senior Support', 'location': 'Mumbai'}

5. Making a Copy Using copy()

# Dictionary representing a user's profile
profile = {
"username": "neo_2025",
"followers": 320,
"verified": False
}

# Making a shallow copy
profile_clone = profile.copy()

print("Original:", profile)
print("Copy:", profile_clone)

Output will look like this:

Original: {'username': 'neo_2025', 'followers': 320, 'verified': False}
Copy: {'username': 'neo_2025', 'followers': 320, 'verified': False}

Nested Dictionaries In Python

Now we will learn how to store a dictionary inside another dictionary. This structure is called a nested dictionary, and it is helpful when you want to group related information in an organized way.

Example:

# A dictionary containing details of multiple devices
devices = {
"deviceA": {
"brand": "TechOne",
"battery": 85,
"wifi": True
},
"deviceB": {
"brand": "MaxPro",
"battery": 40,
"wifi": False
}
}

# Accessing inner dictionary values
print("Brand of deviceA:", devices["deviceA"]["brand"])
print("Is WiFi available in deviceB?", devices["deviceB"]["wifi"])

Expected Output:

Brand of deviceA: TechOne
Is WiFi available in deviceB? False

Iterating Through a Dictionary

A dictionary stores data in key–value pairs, and Python allows you to loop through:

  • Only the keys
  • Only the values
  • Both keys and values together

1) Iterating Through Keys

  • When you loop directly over a dictionary, Python automatically gives you the keys. For example:
# Dictionary storing information about a gadget
gadget = {
"model": "Z-Phone",
"price": 18999,
"storage": "128GB"
}

# Looping through keys
for feature in gadget:
print(feature, "=>", gadget[feature])

Output:

model => Z-Phone
price => 18999
storage => 128GB

2) Iterating Through Key–Value Pairs

Use the .items() method to get both the key and value at the same time. For example:

# Dictionary storing details of a city
city_info = {
"name": "Seaside Town",
"population": 54000,
"has_airport": False
}

# Looping through keys and values
for key, value in city_info.items():
print(f"{key} : {value}")

See the output:

name : Seaside Town
population : 54000
has_airport : False

Use Cases of Python Dictionaries

1) Storing Configuration Data: Applications often need settings like host name, theme, or port number. A dictionary keeps all these details in one place, making them easy to update.

config = {"host": "localhost", "port": 8080}

2) Counting Occurrences:

# Counting the frequency of each fruit manually
fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"]

frequency = {}

for item in fruits:
if item not in frequency:
frequency[item] = 1
else:
frequency[item] += 1

print(frequency)

# Output: {'apple': 3, 'banana': 2, 'cherry': 1}

3) Mapping Keys to Functions: Dictionaries can also act like a mini command center, where each key triggers a different function.

# Simple math functions
def multiply(x, y):
return x * y

def divide(x, y):
return x / y if y != 0 else "Cannot divide by zero"

# Dictionary that maps operation names to functions
actions = {
"mul": multiply,
"div": divide
}

# Calling a function using dictionary key
result = actions["mul"](6, 4)
print("Result:", result)

# Output: Result: 24