Skip to main content

Python Dictionary: Definition, Keys, Values, and Examples

 

✍️Introduction

A dictionary in Python is used to store data in key–value pairs.

It is very useful when you want to store related information like a person’s details, product info, or student records.

  • Dictionaries are written using curly braces {}.

  • Each key in a dictionary must be unique.

  • Dictionaries are mutable, which means we can change their values.

  • They allow fast data access using keys instead of indexes.


What is a Dictionary in Python?

A dictionary is a data structure that stores values in key–value pairs, where each key is used to access its value.

A dictionary is:

  • Dictionaries are ordered (from Python 3.7+).

  • They are changeable (mutable), so values can be updated.

  • Keys must be unique, but values can be duplicated.

Example:

student = {                         # Create a dictionary

    "name": "Rahul",           # Key: name, Value: Rahul

    "age": 20,                       # Key: age, Value: 20

    "course": "Python"        # Key: course, Value: Python

}

print(student)                    # Print the dictionary


Output:
{'name': 'Rahul', 'age': 20, 'course': 'Python'}

"Code executed successfully" 

Note:Dictionaries are commonly used to store structured data like student records or user details.

Dictionary Syntax :

Dictionary syntax defines how to create a dictionary using key–value pairs inside curly brackets {}.

  • A dictionary is created using { }.

  • Each element consists of a key and a value separated by a colon :.

  • Multiple key–value pairs are separated by commas ,.

  • Keys must be unique and usually written as strings or numbers.

Syntax :

dictionary_name = { key1: value1, key2: value2 }

Example:

student = { # Dictionary name "name": "Rutuja", # Key: name, Value: Rahul "age": 20 # Key: age, Value: 20 } print(student) # Print dictionary

Output:
{'name': 'Rutuja', 'age': 20}

"Code executed successfully" 

Note:Keys are used to access values quickly in a dictionary.

Access Dictionary Values :

Dictionary values can be accessed using their keys.

  • We use the key inside square brackets [ ] to access a value.

  • The get() method is another way to access values safely.

  • If the key does not exist, get() returns None instead of an error.

  • Using [] gives an error if the key is missing.

Example:

student = { # Create dictionary "name": "Rutuja", "age": 20, "course": "Python" } print(student["name"]) # Access value using key "name" print(student.get("age")) # Access value using get() method

Output:
Rutuja 20

"Code executed successfully" 

Note:get() is safer than [] because it does not crash the program if the key is missing.

Change Dictionary Values :

Dictionary values can be changed by using the key and assigning a new value.

  • Dictionaries are mutable, so their values can be updated.
  • We use the key inside square brackets [ ] to modify the value.
  • If the key exists, the value is updated.
  • If the key does not exist, a new key–value pair is created.

Example:

student = { # Create dictionary "name": "Rutuja", "age": 20, "course": "Python" } student["age"] = 21 # Change value of key "age" print(student) # Print updated dictionary

Output:
{'name': 'Rutuja', 'age': 21, 'course': 'Python'}

"Code executed successfully" 

Note:Dictionaries allow easy updating of values using keys.

Add New Items:

New items can be added to a dictionary by assigning a value to a new key.

  • Dictionaries are dynamic, so new key–value pairs can be added anytime.
  • If the key does not exist, it will be created automatically.
  • If the key already exists, its value will be updated.
Example:

student = { # Create dictionary "name": "Rutuja", "age": 20 } student["city"] = "Pune" # Add new key "city" with value "Pune" print(student) # Print updated dictionary

Output:
{'name': 'Rutuja', 'age': 20, 'city': 'Pune'}

"Code executed successfully" 

Note:Adding new keys makes dictionaries flexible for storing extra data.

Remove Items from Dictionary :

Items can be removed from a dictionary using different methods like pop(), popitem(), del, and clear().

  • Dictionaries allow deleting specific or all items.

  • pop() removes an item using its key.

  • popitem() removes the last inserted item.

  • del removes a specific key–value pair.

  • clear() removes all items from the dictionary.

Example:

student = { # Create dictionary "name": "Rahul", "age": 20, "course": "Python", "city": "Pune" } student.pop("age") # Removes key "age" print(student) # Print dictionary
student.popitem() # Removes last inserted item ("city") print(student) # Print dictionary
del student["course"] # Deletes key "course" print(student)  # Print dictionary     
 
student.clear() # Removes all items print(student) # Print dictionary

Output:
{'name': 'Rahul', 'course': 'Python', 'city': 'Pune'} {'name': 'Rahul', 'course': 'Python'} {'name': 'Rahul'} {}

"Code executed successfully" 

Note:

  • pop() needs a key.
  • del gives an error if the key does not exist.
  • clear() makes the dictionary empty.

Dictionary Length :

The len() function is used to count the number of key–value pairs in a dictionary.

  • It returns the total number of items in the dictionary.

  • Each key–value pair is counted as one item.

  • Useful for checking how much data is stored.

Example:

student = { # Create dictionary "name": "Rutuja", "age": 20, "city": "Pune" } print(len(student)) # Prints number of items in dictionary

Output:
3

"Code executed successfully" 

Note:len() counts keys, not characters or values.

Loop Through Dictionary:

Looping through a dictionary allows us to access keys, values, or both using loops.

  • A for loop is used to iterate through dictionary items.
  • By default, looping returns keys.
  • .values() returns all values.
  • .items() returns both key and value pairs.
  • Useful for printing or processing dictionary data.

Example:

student = { # Create dictionary "name": "Rutuja", "age": 20, "city": "Pune" } # Loop through keys for key in student: # Iterates through keys print(key) # Prints each key # Loop through values for value in student.values(): # Gets all values print(value) # Prints each value # Loop through keys and values for key, value in student.items(): # Gets key-value pairs print(key, ":", value) # Prints key and value

Output:
name age city Rutuja 20 Pune name : Rutuja age : 20 city : Pune

"Code executed successfully" 

Note:

  • student → keys

  • student.values() → values

  • student.items() → key + value pairs

Dictionary Methods (Common) :

Dictionary methods are built-in functions used to perform operations like accessing, updating, and deleting dictionary data.
  • Methods make dictionaries easier to use and manage.

  • They help in retrieving keys, values, and items quickly.

  • Some methods modify the dictionary, while others only read data.

  • These methods are commonly used in real-world programs and projects.


Method                      Description
keys() Returns keys
values()                        Returns values
items()Returns key–value pairs
get()Access value
update()Update dictionary
pop()Remove item
clear()Remove all

Note:Dictionary methods help in fast and easy data manipulation.

Check if Key Exists :

We can check whether a key exists in a dictionary using the in keyword.

  • The in keyword searches for a key in the dictionary.

  • It returns True if the key exists, otherwise False.

  • This helps avoid errors when accessing dictionary values.

  • It is commonly used before using student["key"].

Example:

student = { # Create dictionary "name": "Rutuja", "age": 20 } if "name" in student: # Check if key "name" exists print("Key exists") # Runs if key is found

Output:
Key exists

"Code executed successfully" 

Note:Using in prevents errors like KeyError when accessing dictionary values.

Nested Dictionary :

A nested dictionary is a dictionary inside another dictionary.

  • It is used to store multiple records in a structured way.

  • Each key can contain another dictionary as its value.

  • Useful for storing student data, employee records, or product details.

  • Data can be accessed using multiple keys.

Example:

students = { "s1": {"name": "Aniket", "age": 20}, # Dictionary inside dictionary "s2": {"name": "Om", "age": 19} # Another nested dictionary } print(students["s1"]["name"]) # Access name of student s1 print(students["s2"]["age"]) # Access age of student s2

Output:
Aniket 19

"Code executed successfully" 

Note:Nested dictionaries help organize complex data in a structured format.

Dictionary with Different Data Types :

A dictionary can store different types of values such as strings, numbers, and booleans in a single structure.

  • Keys are usually strings, but values can be of any data type.

  • Dictionaries can store integers, floats, strings, lists, and booleans together.

  • This makes dictionaries very useful for storing mixed data like program settings or user information.

  • Each value is accessed using its key.

Example:

data = {
    "name": "Python",      # String value
    "version": 3.12,          # Float value
    "is_easy": True          # Boolean value
}

print(data["name"])        # Prints string value
print(data["version"])     # Prints float value
print(data["is_easy"])     # Prints boolean value

Output:
Python 3.12 True

"Code executed successfully" 

Note:Dictionaries allow storing multiple data types in one place, unlike arrays.

Convert Dictionary to List :

A dictionary can be converted into a list by using the list() function along with dictionary methods like keys(), values(), or items().
  • list() converts them into a list format.

  • This is useful when you want to process dictionary data like a list.

  • You can also convert values and key–value pairs into lists.

Example:
student = { # Create dictionary "name": "Rahul", "age": 20, "city": "Pune" } keys_list = list(student.keys()) # Convert dictionary keys into a list print(keys_list) # Print list
Output:
['name', 'age', 'city']

"Code executed successfully" 

Note:
You can also use:

  • list(student.values()) → List of values

  • list(student.items()) → List of key–value pairs

Difference Between List, Tuple, Set, Dictionary :

List, Tuple, Set, and Dictionary are the main data structures in Python used to store collections of data.

Feature        List         Tuple        Set           Dictionary
Ordered            YesYesNoYes
Changeable Yes            No         YesYes
DuplicatesYesYesNoKeys ❌
IndexingYesYesNoKeys

Note:

  • List → General purpose collection

  • Tuple → Fixed data

  • Set → Unique values

  • Dictionary → Key–value data storage

Real-Life Example :

A dictionary can be used to store real-life data such as product details in key–value pairs.

product = { "name": "Laptop", # Product name "price": 50000, # Product price "brand": "HP" # Product brand } print(product["name"]) # Print product name print(product["price"]) # Print product price print(product["brand"]) # Print product brand

Output:
Laptop 50000 HP

"Code executed successfully" 

❌ Common Mistakes :

  • Using duplicate keys

  • Accessing non-existing key without get()

  • Confusing list indexing with dictionary keys

Conclusion :

Python dictionaries are powerful and widely used in real-world applications.
They make data handling easy, readable, and efficient.


💬 Quick Question

What will be the output?

d = {"a":1, "b":2, "a":3} print(d)

Comment your answer 👇😊

📌 Related Articles

Comments

popular

What Is Python Programming? Features, Uses and Career Scope.

  ✍️ Introduction Python is one of the most popular and beginner-friendly programming languages in the world today. It is widely used for web development, data science, artificial intelligence, automation, and software development. Because of its simple syntax and powerful features, Python is an excellent choice for students, beginners, and professionals. In this article, you will learn what Python programming is, its key features, real-life uses, and the career opportunities it offers. 🧠 What Is Python Programming? Python is a high-level, interpreted programming language created to make coding easy and readable. It allows developers to write programs using simple English-like statements, which makes it ideal for beginners. Python supports multiple programming styles such as procedural, object-oriented, and functional programming. ⭐ Features of Python Easy to learn and understand Simple and readable syntax Interpreted language Platform independent Large standard l...

what is Python Date and Time ? Complete Guide with Examples:

  ✍️ Introduction Python provides powerful tools to work with dates and times . The most commonly used module is datetime . The datetime module allows Python programs to create, manipulate, format, and perform calculations with dates and times easily. Date and time handling is used in: Logging systems Attendance & billing systems Data analysis Real-time applications How To Import Date and Time Module : In Python, the datetime module is used to work with dates , times , and date–time combinations . It is part of Python’s standard library, so no installation is required. You can import it in different ways depending on your need. import datetime Get Current Date and Time: This code obtains the current system date and time as a single datetime object using the datetime module. Example: import datetime now = datetime.datetime.now() print (now) Output: 2026-02-13 11:25:53.445827 "Code executed successfully"  Get Only Date: This code retrieves t...

Features of Python Programming Language Explained with Examples

✍️ Introduction Python is one of the most popular programming languages because of its powerful and easy-to-use features. It is designed to make programming simple, readable, and efficient. Python is widely used by beginners as well as professionals due to its flexibility and strong community support. In this article, we will discuss the main features of Python programming language in simple English with easy examples. 🧠 What Are Features of Python? Features of Python are the special characteristics that make it different from other programming languages. These features help programmers write clean, readable, and efficient code with less effort. ⭐ Key Features of Python Programming Language 1️⃣ Easy to Learn and Easy to Use Python has a simple syntax that is close to the English language. This makes it very easy for beginners to learn and understand programming concepts. Example: print("Hello, World!") 2️⃣ Interpreted Language Python is an interpreted language, which me...

Python Operators: Types with Examples

 ✍️Introduction In Python, operators are symbols used to perform operations on variables and values. Operators help us do calculations, comparisons, and logical decisions in programs. In this article, you will learn: • What Python operators are • Types of Python operators • Simple examples for each type