Dictionaries in Python: Operations & Examples Explained | FACE Prep

Dictionaries in Python: Operations & Examples Explained | FACE Prep

 Dictionaries in Python: A Comprehensive Guide

Dictionaries in Python are a versatile and essential data structure that store key-value pairs. Unlike lists, dictionaries are unordered but indexed, allowing efficient retrieval and manipulation of data. Here’s a detailed look at dictionaries, including how to create, access, modify, and delete elements.

What are Dictionaries in Python?

 A dictionary in Python is a collection of key-value pairs where each key is unique and immutable (e.g., strings, integers, tuples), while values can be of any data type and may be repeated. Here’s a quick syntax overview:
# Basic dictionary syntax
my_dict = {
    "key1": "value1",
    "key2": "value2"
}

Creating Dictionaries in Python

Dictionaries can be created using curly braces {} or the dict() method.

Examples:

# Empty dictionary
empty_dict = {}
print(empty_dict)

# Dictionary with key-value pairs
dict1 = {"color": "pink", "shape": "square"}
print(dict1)

# Using the dict() method
dict2 = dict(color="blue", shape="circle")
print(dict2)

Handling Duplicate Keys:

Duplicate keys in a dictionary overwrite previous values. For example:
# Duplicate keys example
dict_example = {"color": "pink", "color": "red"}
print(dict_example)  # Output: {'color': 'red'}
Note: Dictionary keys are case-sensitive, so "Color" and "color" are treated as different keys.

Appending Key-Value Pairs to a Dictionary

Using update() Method:

The update() method is ideal for adding multiple key-value pairs or merging dictionaries.
# Adding elements to an empty dictionary
dict1 = {}
dict1.update({"color": "blue", "shape": "round"})
print(dict1)

# Merging dictionaries
dict2 = {"size": "small"}
dict1.update(dict2)
print(dict1)

Adding with Keys:

You can directly assign a new key-value pair.
# Adding a single key-value pair
dict1["length"] = "14cm"
print(dict1)

Accessing Values in a Dictionary

Using Keys:

You can access a value by specifying its key.
# Accessing a value
dict1 = {"color": "pink", "shape": "square"}
print(dict1["shape"])  # Output: square

Using get() Method:

The get() method is safer as it avoids errors if the key is missing.
# Accessing a value using get()
print(dict1.get("shape"))  # Output: square
print(dict1.get("size", "Key not found"))  # Output: Key not found

Modifying Key-Value Pairs in a Dictionary

You can update a dictionary by reassigning values to an existing key.
# Modifying a value
dict1 = {"color": "pink", "shape": "square"}
dict1["color"] = "blue"
print(dict1)  # Output: {'color': 'blue', 'shape': 'square'}

Deleting Key-Value Pairs from a Dictionary

Using pop() Method:

Removes a specific key-value pair.
# Using pop()
dict1 = {"color": "pink", "shape": "square"}
dict1.pop("color")
print(dict1)  # Output: {'shape': 'square'}

Using del Statement:

Deletes a specific key or the entire dictionary.
# Deleting a key-value pair
del dict1["shape"]
print(dict1)  # Output: {}

# Deleting the entire dictionary
del dict1

Using clear() Method:

Removes all elements from a dictionary, leaving it empty.
# Using clear()
dict1 = {"color": "pink", "shape": "square"}
dict1.clear()
print(dict1)  # Output: {}

Limitations of Dictionaries

  • No Slicing: Unlike lists, dictionaries do not support slicing as they are unordered.

Dictionary Methods in Python

Here are some essential methods for dictionary operations:
MethodDescription
keys()Returns a view object of all the keys.
values()Returns a view object of all the values.
items()Returns a view object of key-value pairs.
pop()Removes a specified key-value pair.
popitem()Removes the last inserted key-value pair.
clear()Clears all elements in the dictionary.
update()Adds or updates key-value pairs.

Why Choose Dictionaries Over Lists?

Dictionaries excel in scenarios where quick lookups are required. Unlike lists, dictionaries allow efficient retrieval of values using keys. For instance, searching for an element in a list requires a linear search, whereas dictionaries offer constant-time complexity for key lookups.

Conclusion

Dictionaries in Python are powerful tools for organizing and managing data. Their ability to store unique keys with associated values makes them indispensable for various programming tasks. By mastering the techniques outlined here, you can efficiently leverage dictionaries in your Python projects. Click here to know more our program!
c