[Latest] Python Dictionary with Examples – Easiest Explanation – 2024

In the world of Python programming, the Python dictionary stands out as a versatile and essential data structure. It provides a way to store and manage data in key-value pairs, allowing for efficient retrieval and manipulation. With its flexibility and wide range of applications, the Python dictionary has become a go-to tool for many developers.

In this article, we will explore the fundamentals of Python dictionaries and discuss their key features and benefits.

At its core, a dictionary is an unordered collection of items, where each item consists of a key and its associated value. The key serves as a unique identifier and allows for quick and direct access to the corresponding value. This makes dictionaries particularly useful when you need to search for, retrieve, or modify data based on specific keys.

Creating a Python Dictionary

Creating a dictionary in Python is straightforward. You can use curly braces {} or the built-in dict() function to define an empty dictionary. To add items, you simply assign values to their respective keys, enclosed in square brackets []. For example:

my_dict = {}  # empty dictionary
my_dict['name'] = 'John'  # adding a key-value pair
my_dict['age'] = 30
print(my_dict)

Output

{'name':'John','age':30}

Alternatively, you can initialize a dictionary with pre-defined key-value pairs:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

One of the main advantages of dictionaries is their ability to handle a wide variety of data types for both keys and values. You can use integers, strings, floats, tuples, or even other dictionaries as keys. Values can be of any data type, such as numbers, strings, lists, or even complex objects. This flexibility allows dictionaries to accommodate diverse and complex data structures.

Accessing values from a Python Dictionary

Retrieving values from a dictionary is extremely efficient. Instead of iterating over the entire collection, as in the case of lists, dictionaries use a process called hashing. The key’s hash value serves as an index, pointing directly to the corresponding value. As a result, even with large dictionaries, retrieval operations are performed in constant time, regardless of the dictionary’s size.

To access a value, you simply provide the corresponding key inside square brackets:

name = my_dict['name']  # retrieves the value associated with 'name'
print(name)

Output

John

However, it’s important to note that accessing a key that doesn’t exist in the dictionary will result in a KeyError. To avoid this, you can use the get() method, which returns either the value associated with the given key or a default value if the key is not found:

name = my_dict.get('name', 'Unknown')  # returns 'Unknown' if 'name' is not found
surname = my_dict.get('surname', 'Unknown')  # returns 'Unknown' if 'name' is not found

print(name)
print(surname)

Output

John
Unknown

Dictionaries also offer various methods to manipulate and transform data. You can update or modify existing values by simply reassigning them. Adding new key-value pairs or deleting existing ones can be achieved using the update() and del statements, respectively. Additionally, the keys(), values(), and items() methods provide access to the dictionary’s keys, values, and key-value pairs, allowing for convenient iteration and extraction of data.

Nested Python Dictionary

A nested Python dictionary is a dictionary that contains other dictionaries as values. It allows for the creation of hierarchical data structures where dictionaries are nested within one another. This nesting can be done to any depth, enabling the representation of complex and structured data.

To illustrate the concept, let’s consider an example of a nested dictionary representing a company’s employee database:

company = {
    'employees': {
        'John': {
            'age': 30,
            'position': 'Manager',
            'salary': 50000
        },
        'Jane': {
            'age': 25,
            'position': 'Developer',
            'salary': 40000
        },
        'Mark': {
            'age': 35,
            'position': 'Analyst',
            'salary': 45000
        }
    },
    'departments': {
        'IT': ['John', 'Jane'],
        'Finance': ['Mark']
    }
}
Nested Python Dictionary

In this example, we have a dictionary named company with two main keys: ’employees’ and ‘departments’. The ’employees’ key holds a nested dictionary where employee names are the keys, and their details (age, position, salary) are stored as the corresponding values. Similarly, the ‘departments’ key holds another nested dictionary where department names are the keys, and the employees working in each department are stored as lists.

To access specific information in a nested dictionary, we can chain the square brackets. For example, to retrieve the age of John, we can use the following:

print(company['employees']['John']['age'])

Output

30

To add or modify values in a nested dictionary, we follow the same approach by specifying the keys at each level. For instance, to change Jane’s salary, we can do the following:

company['employees']['Jane']['salary'] = 42000

Python Dictionary Methods

MethodDescription
dic.clear()Remove all the elements from the dictionary
dict.copy()Returns a copy of the dictionary
dict.get(key, default = “None”) Returns the value of specified key
dict.items() Returns a list containing a tuple for each key value pair
dict.keys() Returns a list containing dictionary’s keys
dict.update(dict2)Updates dictionary with specified key-value pairs
dict.values() Returns a list of all the values of dictionary
pop() Remove the element with specified key
popItem()Removes the last inserted key-value pair
 dict.setdefault(key,default= “None”)set the key to the default value if the key is not specified in the dictionary
dict.has_key(key)returns true if the dictionary contains the specified key.
dict.get(key, default = “None”)used to get the value specified for the passed key.

Python Dictionary Example

Certainly! Let’s illustrate the concepts discussed by providing an example that demonstrates the usage of Python dictionaries.

# Creating a python dictionary to store student information
student = {
    'name': 'John Doe',
    'age': 20,
    'major': 'Computer Science',
    'grades': [85, 90, 92, 88],
    'contact': {
        'email': 'johndoe@example.com',
        'phone': '123-456-7890'
    }
}

# Accessing values in the dictionary
print("Student Name:", student['name'])
print("Age:", student['age'])
print("Major:", student['major'])
print("Grades:", student['grades'])
print("Email:", student['contact']['email'])

# Modifying values in the dictionary
student['age'] = 21
student['grades'].append(95)

# Adding new key-value pairs
student['address'] = '123 Main St'

# Deleting a key-value pair
del student['contact']

# Iterating over dictionary keys
print("Dictionary Keys:")
for key in student.keys():
    print(key)

# Iterating over dictionary values
print("Dictionary Values:")
for value in student.values():
    print(value)

# Iterating over dictionary key-value pairs
print("Dictionary Items:")
for key, value in student.items():
    print(key, ":", value)

Output

Student Name: John Doe
Age: 20
Major: Computer Science
Grades: [85, 90, 92, 88]
Email: johndoe@example.com
Dictionary Keys:
name
age
major
grades
address
Dictionary Values:
John Doe
21
Computer Science
[85, 90, 92, 88, 95]
123 Main St
Dictionary Items:
name : John Doe
age : 21
major : Computer Science
grades : [85, 90, 92, 88, 95]
address : 123 Main St

In this example, we create a dictionary called student to store information about a student. The dictionary contains various key-value pairs such as ‘name’, ‘age’, ‘major’, ‘grades’, and ‘contact’. The ‘contact’ key itself holds another dictionary with ’email’ and ‘phone’ keys.

Demonstrate Data inside the student dictionary

We then demonstrate how to access values in the dictionary using square brackets and the corresponding keys. We can access nested values by chaining the square brackets. For example, to access the student’s email, we use student['contact']['email'].

Modify Data inside the student dictionary

Next, we modify values in the dictionary by reassigning the ‘age’ key and appending a grade to the ‘grades’ key.

Adding Data inside the student dictionary

We also demonstrate how to add new key-value pairs to the dictionary using the assignment. In this case, we add the ‘address’ key.

Delete Data inside the student dictionary

To delete a key-value pair, we use the del statement and specify the key we want to remove from the dictionary.

Iterating over key-value pairs inside the student dictionary

Furthermore, we show how to iterate over the dictionary’s keys, values, and key-value pairs using the keys(), values(), and items() methods, respectively.

By running this example, you can observe the power and versatility of Python dictionaries in managing and manipulating data efficiently.

Conclusion

In conclusion, Python dictionaries are a fundamental tool for efficient data management. Their ability to store and retrieve data based on unique keys, coupled with the flexibility to handle different data types, makes them indispensable in a wide range of programming scenarios. Whether you need to build a lookup table, organize complex data structures, or optimize data retrieval, dictionaries provide an elegant and powerful solution. So, embrace the power of dictionaries and unlock the full potential of your Python programs.

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *