DEV Community

Cover image for Python Dictionary.
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

Python Dictionary.

Python Dictionary: A Complete Beginner's Guide with Examples

Introduction

Python is one of the most popular programming languages, widely used in web development, automation, data science, and artificial intelligence. One of its most useful built-in data structures is the Dictionary.

A Dictionary allows developers to store and manage information in key-value pairs. Instead of accessing data using numerical indexes like lists, we can retrieve information using meaningful keys.

For example, consider a Student Management System. We need to store student details such as ID, name, department, age, and marks. A Python Dictionary makes it easy to organize and access these details.

In this blog, we will explore Python Dictionaries, including their creation, accessing keys and values, iteration, condition checking, adding, updating, deleting, nested dictionaries, and practical coding examples.

1. What Is a Dictionary in Python?

A Dictionary is a built-in Python data structure that stores information in key-value pairs.

Each key is associated with a value.

Syntax:

dictionary_name = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}
Enter fullscreen mode Exit fullscreen mode

Example:

student = {
    "id": 101,
    "name": "Ravi",
    "department": "IT",
    "age": 22,
    "marks": 85
}

print(student)
Enter fullscreen mode Exit fullscreen mode

Output:

{
    'id': 101,
    'name': 'Ravi',
    'department': 'IT',
    'age': 22,
    'marks': 85
}
Enter fullscreen mode Exit fullscreen mode

Here, id, name, department, age, and marks are keys, while 101, Ravi, IT, 22, and 85 are their corresponding values.

Important characteristics of Dictionary

  • Stores data in key-value pairs.
  • Keys must be unique.
  • Values can be duplicated.
  • Dictionaries are mutable, meaning we can modify their contents.
  • Dictionaries preserve insertion order.
  • Keys must be hashable, such as strings, numbers, or suitable tuples.
  • Values can contain different data types.

2. Creating a Dictionary

There are different ways to create a dictionary in Python.

Using curly braces:

student = {
    "name": "Ravi",
    "age": 22,
    "marks": 85
}

print(student)
Enter fullscreen mode Exit fullscreen mode

Creating an empty dictionary:

student = {}

student["name"] = "Ravi"
student["age"] = 22

print(student)
Enter fullscreen mode Exit fullscreen mode

Using the dict() function:

student = dict(name="Ravi", age=22, marks=85)

print(student)
Enter fullscreen mode Exit fullscreen mode

All three approaches create a dictionary containing student details.

3. Accessing Dictionary Values

We can retrieve values using their corresponding keys. Python provides two common approaches.

Using square brackets []

student = {
    "name": "Ravi",
    "age": 22,
    "marks": 85
}

print(student["name"])
print(student["age"])
Enter fullscreen mode Exit fullscreen mode

Output:

Ravi
22
Enter fullscreen mode Exit fullscreen mode

If the specified key does not exist, Python raises a KeyError.

Using the get() method

The get() method retrieves a value without raising an error when a key is missing.

student = {
    "name": "Ravi",
    "age": 22
}

print(student.get("name"))
print(student.get("department"))
print(student.get("department", "Not Available"))
Enter fullscreen mode Exit fullscreen mode

Output:

Ravi
None
Not Available
Enter fullscreen mode Exit fullscreen mode

The main difference is that square brackets raise a KeyError for a missing key, whereas get() returns None by default or a specified default value.

4. Understanding Keys and Values

Python provides three important methods to work with dictionary elements.

keys()

The keys() method returns all keys in a dictionary.

student = {
    "id": 101,
    "name": "Ravi",
    "department": "IT",
    "marks": 85
}

print(student.keys())
Enter fullscreen mode Exit fullscreen mode

Output:

dict_keys(['id', 'name', 'department', 'marks'])
Enter fullscreen mode Exit fullscreen mode

values()

The values() method returns all values in a dictionary.

print(student.values())
Enter fullscreen mode Exit fullscreen mode

Output:

dict_values([101, 'Ravi', 'IT', 85])
Enter fullscreen mode Exit fullscreen mode

items()

The items() method returns all key-value pairs as tuples.

print(student.items())
Enter fullscreen mode Exit fullscreen mode

Output:

dict_items([
    ('id', 101),
    ('name', 'Ravi'),
    ('department', 'IT'),
    ('marks', 85)
])
Enter fullscreen mode Exit fullscreen mode

These three methods are especially useful when working with dictionary data.

5. Iterating Through a Dictionary

Iteration means accessing dictionary elements one by one using a loop.

Python supports different approaches to dictionary iteration.

Iterating through keys

When we directly use a dictionary inside a for loop, Python iterates through its keys.

student = {
    "name": "Ravi",
    "age": 22,
    "department": "IT"
}

for key in student:
    print(key)
Enter fullscreen mode Exit fullscreen mode

Output:

name
age
department
Enter fullscreen mode Exit fullscreen mode

We can also use student.keys() to achieve the same result.

Iterating through values

If we only want the values, we can use the values() method.

for value in student.values():
    print(value)
Enter fullscreen mode Exit fullscreen mode

Output:

Ravi
22
IT
Enter fullscreen mode Exit fullscreen mode

Iterating through keys and values

If we need both keys and values, we can use the items() method.

for key, value in student.items():
    print(key, ":", value)
Enter fullscreen mode Exit fullscreen mode

Output:

name : Ravi
age : 22
department : IT
Enter fullscreen mode Exit fullscreen mode

Here, the first variable receives the key and the second variable receives its corresponding value.

6. Condition Checking in Dictionary

Condition checking helps us identify whether a particular key or value exists in a dictionary.

Checking whether a key exists

We use the in operator to check whether a key is present.

student = {
    "name": "Ravi",
    "age": 22,
    "department": "IT"
}

if "name" in student:
    print("Name exists")
else:
    print("Name does not exist")
Enter fullscreen mode Exit fullscreen mode

Output:

Name exists
Enter fullscreen mode Exit fullscreen mode

Checking whether a key does not exist

We use the not in operator.

if "marks" not in student:
    print("Marks not found")
else:
    print("Marks found")
Enter fullscreen mode Exit fullscreen mode

Output:

Marks not found
Enter fullscreen mode Exit fullscreen mode

Checking whether a value exists

To check whether a particular value is present, we use values().

if "Ravi" in student.values():
    print("Student found")
else:
    print("Student not found")
Enter fullscreen mode Exit fullscreen mode

Output:

Student found
Enter fullscreen mode Exit fullscreen mode

Remember that in directly on a dictionary checks keys, not values.

7. Adding and Updating Dictionary Elements

Dictionaries are mutable, so we can add new elements and modify existing values.

Adding elements

We can add a new key-value pair using square brackets.

student = {
    "name": "Ravi",
    "age": 22
}

student["department"] = "IT"
student["marks"] = 85

print(student)
Enter fullscreen mode Exit fullscreen mode

Output:

{'name': 'Ravi', 'age': 22, 'department': 'IT', 'marks': 85}
Enter fullscreen mode Exit fullscreen mode

Updating existing elements

We can update a value by assigning a new value to an existing key.

student["marks"] = 95

print(student)
Enter fullscreen mode Exit fullscreen mode

Output:

95
Enter fullscreen mode Exit fullscreen mode

Using update()

The update() method allows us to add or modify multiple key-value pairs.

student.update({
    "age": 23,
    "marks": 90
})

print(student)
Enter fullscreen mode Exit fullscreen mode

The update() method modifies existing keys and adds new keys when necessary.

8. Removing Elements from a Dictionary

Python provides several methods to remove dictionary elements.

pop()

Removes a specified key and returns its value.

student = {
    "name": "Ravi",
    "age": 22,
    "marks": 85
}

student.pop("age")

print(student)
Enter fullscreen mode Exit fullscreen mode

popitem()

Removes and returns the last inserted key-value pair.

student.popitem()

print(student)
Enter fullscreen mode Exit fullscreen mode

del keyword

Deletes a specified key-value pair.

del student["name"]

print(student)
Enter fullscreen mode Exit fullscreen mode

clear()

Removes all elements from the dictionary.

student.clear()

print(student)
Enter fullscreen mode Exit fullscreen mode

Output:

{}
Enter fullscreen mode Exit fullscreen mode

9. Nested Dictionary

A nested dictionary means storing one dictionary inside another dictionary.

It is useful when managing multiple records, such as students, employees, and products.

Example: Student Management System

students = {

    101: {
        "name": "Ravi",
        "department": "IT",
        "marks": 85
    },

    102: {
        "name": "Kumar",
        "department": "CSE",
        "marks": 90
    },

    103: {
        "name": "Arun",
        "department": "ECE",
        "marks": 75
    }

}

print(students[101]["name"])
print(students[102]["marks"])
Enter fullscreen mode Exit fullscreen mode

Output:

Ravi
90
Enter fullscreen mode Exit fullscreen mode

We can also iterate through a nested dictionary.

for student_id, details in students.items():

    print("Student ID:", student_id)

    for key, value in details.items():

        print(key, ":", value)

    print()
Enter fullscreen mode Exit fullscreen mode

This approach is commonly used when handling structured data and JSON responses from backend APIs.

10. Useful Dictionary Functions and Methods

Some additional built-in functions and dictionary methods are important for everyday programming.

Method or function Purpose
len(d) Returns the number of key-value pairs
get() Retrieves a value
keys() Returns all keys
values() Returns all values
items() Returns key-value pairs
update() Adds or updates elements
pop() Removes a specified key
popitem() Removes the last inserted pair
clear() Removes all elements
copy() Creates a shallow copy
setdefault() Returns a value or inserts a default
fromkeys() Creates a dictionary from given keys

Example using len():

student = {
    "name": "Ravi",
    "age": 22,
    "marks": 85
}

print(len(student))
Enter fullscreen mode Exit fullscreen mode

Output:

3
Enter fullscreen mode Exit fullscreen mode

11. Real-World Coding Example: Employee Management System

Let's combine the dictionary concepts we have learned to create a simple Employee Management System.

employees = {

    101: {
        "name": "Ravi",
        "department": "IT",
        "salary": 25000
    },

    102: {
        "name": "Kumar",
        "department": "HR",
        "salary": 30000
    },

    103: {
        "name": "Arun",
        "department": "IT",
        "salary": 28000
    }

}

# Display all employees

for emp_id, details in employees.items():

    print("Employee ID:", emp_id)
    print("Name:", details["name"])
    print("Department:", details["department"])
    print("Salary:", details["salary"])

    print("-------------------")


# Search employee

search_id = 102

if search_id in employees:

    print("Employee Found")
    print("Name:", employees[search_id]["name"])

else:

    print("Employee Not Found")


# Update salary

employees[101]["salary"] = 35000

print("Updated Salary:", employees[101]["salary"])
Enter fullscreen mode Exit fullscreen mode

This example combines dictionary creation, nested dictionaries, iteration, condition checking, accessing values, and updating elements.

These operations are frequently used in real-world backend applications.

12. Common Dictionary Coding Interview Problems

Practising dictionary-based problems helps beginners improve their logical thinking and programming skills.

Problem 1: Count the frequency of characters

Question: Count how many times each character appears in a string.

text = "programming"

frequency = {}

for char in text:

    if char in frequency:

        frequency[char] = frequency[char] + 1

    else:

        frequency[char] = 1

print(frequency)
Enter fullscreen mode Exit fullscreen mode

Output:

{
    'p': 1,
    'r': 2,
    'o': 1,
    'g': 2,
    'a': 1,
    'm': 2,
    'i': 1,
    'n': 1
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Create an empty dictionary.
  2. Iterate through every character in the string.
  3. Check whether the character already exists.
  4. If it exists, increase its count by one.
  5. Otherwise, insert the character with a value of one.

Problem 2: Find the student with the highest marks

students = {
    "Ravi": 85,
    "Kumar": 90,
    "Arun": 75,
    "Priya": 95
}

highest = 0
topper = ""

for name, marks in students.items():

    if marks > highest:

        highest = marks
        topper = name

print("Topper:", topper)
print("Highest Marks:", highest)
Enter fullscreen mode Exit fullscreen mode

Output:

Topper: Priya
Highest Marks: 95
Enter fullscreen mode Exit fullscreen mode

Problem 3: Find students with marks greater than 50

marks = {
    "Ravi": 85,
    "Kumar": 40,
    "Arun": 75,
    "Priya": 35
}

for name, mark in marks.items():

    if mark > 50:

        print(name, mark)
Enter fullscreen mode Exit fullscreen mode

Output:

Ravi 85
Arun 75
Enter fullscreen mode Exit fullscreen mode

Problem 4: Merge two dictionaries

dict1 = {
    "name": "Ravi",
    "age": 22
}

dict2 = {
    "department": "IT",
    "marks": 85
}

dict1.update(dict2)

print(dict1)
Enter fullscreen mode Exit fullscreen mode

Output:

{
    'name': 'Ravi',
    'age': 22,
    'department': 'IT',
    'marks': 85
}
Enter fullscreen mode Exit fullscreen mode

13. Time Complexity of Python Dictionary

Python Dictionaries use hash tables internally to store and retrieve data efficiently.

Operation Average Time Complexity
Insert O(1)
Access O(1)
Update O(1)
Delete O(1)
Search key O(1)
Iterate through dictionary O(n)

These are average-case complexities. In collision-heavy situations, individual operations can take O(n).

14. Real-World Applications of Python Dictionary

Python Dictionaries are used in many areas of software development.

  1. Student Management Systems: Store student IDs and their personal or academic details.
  2. Employee Management Systems: Store employee IDs, names, departments, and salaries.
  3. URL Shorteners: Store short codes as keys and original URLs as values.
  4. E-commerce Applications: Store product IDs and product information.
  5. Frequency Counting: Count how many times characters or elements appear.
  6. API Development: Handle JSON request and response data.
  7. Caching: Store previously retrieved information for faster access.

Conclusion

Python Dictionary is one of the most important built-in data structures for storing and managing information in key-value pairs.

Understanding dictionary operations such as keys(), values(), items(), iteration, condition checking, adding, updating, deleting, and nested dictionaries is essential for every Python developer.

Dictionaries are widely used in backend development, API integration, automation, data processing, and real-world software applications.

For beginners, practising dictionary-based coding problems is an excellent way to strengthen programming fundamentals and improve problem-solving skills.

Keep learning, keep coding, and build your programming fundamentals step by step!

Top comments (0)