Data Structures in Python
Data Structures in Python
Introduction
Data structures play a pivotal role in computer science and programming, as they are essential for storing,
organizing, and manipulating data efficiently.
Python, a versatile and popular programming language, provides a wide array of data structures to
accommodate various needs
Data Handling: Programming often involves working with data, which can be numbers, text, or more
complex information. Data structures are like specialized containers that help us manage this data
efficiently
Organization: Just as you use different shelves, drawers, and containers at home to organize various
items, in programming, you use different data structures to organize different types of data
Efficiency: The choice of data structure can significantly impact how quickly you can access, manipulate,
and process your data. Picking the right data structure is crucial for writing efficient code
Flexibility: Different data structures serve different purposes. Some are great for storing lots of data, while
others are optimized for quick searches or data retrieval
Built-in Tools: Python provides a rich set of built-in data structures that make it easier for programmers to
handle common data management tasks without having to build everything from scratch
Real-World Analogy: You can think of data structures as tools in your toolbox. For example, if you want to
organize your books, you might use a bookshelf (analogous to a list). If you want to store unique items,
like a collection of rare coins, you'd use a display case (analogous to a set)
Custom Data Structures: In addition to built-in data structures, Python allows you to create custom data
structures to suit your specific needs. This is akin to crafting your own unique container for a particular
purpose.
numbers = [1, 2, 3, 4, 5]
Output:
Example 2:
Phones.append("Oppo")
Phones.remove("Mi")
Output:
Example 3:
name = info[0]
age = info[1]
print("Name:", name)
print("Age:", age
Output:
Name: Julie
Age: 21
Example 4:
element = matrix[1][2]
Output:
It's like having a piece of paper where you jot down items you need to buy at the grocery store. Each item is a
list element.
You can add new items, remove items, or check if a specific item is on the list.
Code:
item_to_check = "Milk"
if item_to_check in shopping_list:
else:
Output:
Tuple
Once you create a tuple, you cannot change its content. This immutability makes tuples useful for
situations where you want to ensure that the data remains constant.
Example 1:
point = (3, 4)
print("Y-coordinate:", point[1])
Output:
X-coordinate: 3
Y-coordinate: 4
Example 2:
Output:
Example 3:
def get_student_info():
name = "Arun"
age = 21
grade = "A"
student_info = get_student_info()
Output:
Example 4:
Output:
print("Box contents:")
Output:
Box contents:
- Dark Chocolate
- Milk Chocolate
- White Chocolate
Box contents:
- Caramel Chocolate
- Hazelnut Chocolate
Box contents:
- Raspberry Chocolate
- Coconut Chocolate
Set
Sets are unordered collections of unique elements. They are useful when you need to work with distinct items
and perform set operations like union, intersection, and difference.
Sets are mutable, so you can add and remove elements, but the elements themselves must be immutable.
Example 1:
# Create a set of favorite colors
print(favorite_colors)
Output:
{'green', 'yellow', 'blue', 'red'}
Example 2:
shopping_list = set()
shopping_list.add("apples")
shopping_list.add("bananas")
shopping_list.add("milk")
print(shopping_list)
Output:
Example 3:
passed_courses.remove("Math")
print(passed_courses)
Output:
Example 4:
all_fruits = fruits_set_1.union(fruits_set_2)
print(all_fruits)
Output:
Real-World Analog
Think of a set as your shopping list. You want to buy specific items at the grocery store. Your shopping list
contains unique items, and you can add or remove items as needed. You don't want duplicates on your list,
and you can quickly check whether an item is on your list or not. If you decide not to buy an item, you remove
shopping_list = set()
shopping_list.add("apples")
shopping_list.add("bananas")
shopping_list.add("milk")
if "apples" in shopping_list:
else:
shopping_list.discard("milk")
if "milk" in shopping_list:
else:
Output:
You need to buy apples.
Dictionarie
Dictionaries are key-value pairs that allow you to store and retrieve data based on a unique key. The keys
must be immutable, such as strings or numbers.
Dictionaries are useful for storing data that needs to be accessed quickly and efficiently.
Example 1:
print(my_dict)
type(my_dict)
Output:
{'Course': 'PWIOI', 'Duration': 2, 'city': 'Banglore'}
Example 2
phonebook = {
Output:
{'PW Customer care': 1234567890, 'PW Team': 9876543210, 'PW Enquiry': 5555555555, 'PW Admmision Dep':
3333333333, 'PWIOI Teacher': 8888888888}
Example 3
student_grades = {
'Jeni': 85,
'jimmy': 92,
'Sindu': 78,
'Akil': 95,
'Chaitu': 89
Output:
{'Jeni': 85, 'jimmy': 92, 'Sindu': 78, 'Akil': 95, 'Chaitu': 89}
Example 4
movie_ratings = {
'Inception': 4.5,
movie_ratings
Output:
{'Inception': 4.5, 'The Shawshank Redemption': 4.7, 'Pulp Fiction': 4.2, 'The Godfather': 4.6, 'Forrest Gump': 4.4}
Real-World Analog
Let'sconsider a real-world analogy for a dictionary using a Product Catalog. Imagine you're running an
online store, and you need to keep track of the prices of various products in your catalog. Here's a Python
code example along with a real-world analogy.
Code:
product_catalog = {
Output:
The price of the iPhone 13 is $999.99
Array
In Python, arrays are similar to lists, but they are more efficient for working with numerical data. To use
‘arrays’, you need to import the array module from the ‘array’ library.
Arrays provide a memory-efficient way to work with large datasets of the same data type.
Example 1
#Temperature Readings:
Output:
array('i', [75, 76, 74, 72, 71, 73, 77])
Example 2
student_scores
Output:
Example 3
stock_prices
Output:
Example 4
employee_ages
Output:
Code:
Your list will consist of various items that you need to buy at
the store.
# You can also update the quantities, for example, if you decide
Output:
Your Grocery Shopping List:
Apples: 3
Bananas: 2
Bread: 1
Milk: 4
Eggs: 2
Apples: 3
Bananas: 2
Bread: 1
Milk: 2
Eggs: 2
Introduction To Lists
Lists in Python are ordered collections of items, where each item can be of any data type
Lists are defined by enclosing a comma-separated sequence of items within square brackets ‘[]’
Lists in Python are similar to arrays in other programming languages but are more versatile because they
can store different data types in the same list.
Creating a List
You can create a list by simply assigning a sequence of values to a variable using square brackets
Lists can contain a mix of data types, such as integers, strings, and booleans.
Code:
#Example-1
print(grocery_list)
Output:
['apples', 'bananas', 'milk', 'eggs', 'bread']
#Example-2
print(todo_list)
Output:
['workout', 'meeting', 'buy groceries', 'pay bills']
#Example-3
print(students)
Output:
['Arun', 'Arjun', 'Charle', 'David', 'Eva']
Accessing Elements
Indexing and slicin
Lists are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on
You can access elements by using square brackets and the index of the element.
Code:
#Example-1
first_page = book_pages[0]
chapter_1_to_3 = book_pages[1:4]
print(chapter_1_to_3)
Output:
['Chapter 1', 'Chapter 2', 'Chapter 3']
#Example-2
playlist = ["Song 1", "Song 2", "Song 3", "Song 4", "Song 5"]
song_2 = playlist[1]
sub_playlist = playlist[2:5]
print(sub_playlist)
Output:
#Example-4
period of time.
"Presentation"]
appointment = calendar[3]
busy_schedule = calendar[1:4]
print(appointment)
print(busy_schedule)
Output:
Appointment
#Example-5
marathon of movies.
selected_movie = movies[2]
movie_marathon = movies[0:4]
print(selected_movie)
print(movie_marathon)
Output:
Horror Movie ['Action Movie', 'Comedy Movie', 'Horror Movie', 'Sci-Fi Movie']
Negative indexing
Negative indexing allows you to access elements from the end of the list
‘-1’ represents the last element, ‘-2’ the second-to-last, and so on.
Code:
#Example-1:
#Analogy: Imagine a book where the last page is -1, the second-
"Index"]
last_page = pages[-1]
second_last_page = pages[-2]
print(last_page)
print(second_last_page)
Output:
Index
Conclusion
#Example-2
starting from the last person (the person at the end of the
last_person = queue[-1]
second_last_person = queue[-2]
print(last_person)
print(second_last_person)
Output:
David
Karan
#Example-3
last_song = playlist[-1]
second_last_song = playlist[-2]
print(last_song)
print(second_last_song)
Output:
Katakali
Sal-sa
#Example-4
#Analogy: On a film reel, the final frame can be seen as -1, the
last_frame = film_reel[-1]
second_last_frame = film_reel[-2]
print(last_frame)
print(second_last_frame)
Output:
Frame 4
Frame 3
#Example-5
days_of_month = ["Day 1", "Day 2", "Day 3", "Day 4", "Last Day"]
last_day = days_of_month[-1]
second_last_day = days_of_month[-2]
print(last_day)
print(second_last_day)
Output:
Last Day
Day 4
Modifying Lists
Append metho
The append() method is used to add an element to the end of a list
It modifies the original list by adding a new element
It is a common operation when you want to add new data or elements to an existing list.
Code:
#Example-1
shopping_cart = []
shopping_cart.append("apples")
shopping_cart.append("bananas")
print(shopping_cart)
Output:
['apples', 'bananas']
#Example-2
tower = []
tower.append("brick1")
tower.append("brick2")
print(tower)
Output:
['brick1', 'brick2']
#Example-3
playlist = []
playlist.append("song1")
playlist.append("song2")
print(playlist)
Output:
['song1', 'song2']
#Example-4
bookshelf = []
bookshelf.append("book1")
bookshelf.append("book2")
print(bookshelf)
Output:
['book1', 'book2']
#Example-5
inventory = []
inventory.append("item1")
inventory.append("item2")
print(inventory)
Output:
['item1', 'item2']
Insert method
The insert() method allows you to add an element at a specified index in the list
It also modifies the original list.
Code:
#Example-1
recipe
Output:
#Example-2
seated in specific seats. You can use the insert() method to add
bus_seats.insert(1, "David")
bus_seats
Output:
#Example-3
bookshelf.insert(0, "Biography")
bookshelf
Output:
#Example-4
insert() method.
deck
Output:
#Example- 5
sala d
Output:
Extend method()
The extend() method is used to append elements from another iterable (e.g., a list or tuple) to the end of the
list
#Example-1
#Analogy: Imagine you have a shopping list, and your friend has
my_list.extend(friend_list)
my_list
Output:
#Example-2
#Analogy: If you have a notebook with some pages filled, and you
notebook.extend(additional_pages)
notebook
Output:
#Example-3
datasets, and you want to combine them into a single dataset for
analysis.
combined_data = []
combined_data.extend(report1_data)
combined_data.extend(report2_data)
combined_data
Output:
my_books.extend(additional_shelf)
my_books
Output:
['Book A', 'Book B', 'Book C', 'Book D']
#Example-5
#Analogy: When cooking, you may have some ingredients in one bowl
and others in a different bowl. To make a complete recipe, you
extend one bowl with the ingredients from the other.
mixing_bowl1.extend(mixing_bowl2)
mixing_bowl1
Output:
['Flour', 'Sugar', 'Eggs', 'Milk']
List Operations:
Concatenation operation
You can concatenate two or more lists using the + operator
This creates a new list without modifying the original lists.
Code:
#Example-1
combined_ingredients
Output:
['flour', 'sugar', 'eggs', 'milk', 'butter', 'chocolate']
#Example-2
combined_catalog
Output:
['Science Fiction', 'Mystery', 'Biography', 'History', 'Cooking', 'Self-Help']
#Example-3
combined_cart
Output:
['item1', 'item2', 'item3', 'item4', 'item5']
#Example-4
full_day_attendance
Output:
['student1', 'student2', 'student3', 'student4', 'student5']
#Example-5
#Analogy: You have two playlists of your favorite songs, one for
pop music and another for rock music. You want to create a new
playlist that combines both genres.
combined_playlist
Output:
Repetition Operation:
This creates a new list with repeated elements without modifying the original list.
Code:
#Example-1
pattern = "*" * 5
print(pattern)
Output:
*****
#Example-2
border = "-" * 20
print(border)
Output:
--------------------
#Example-3
zeros = [0] * 10
print(zeros)
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
#Example-4
print(sequence)
Output:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
#Example-5
reminders = message * 3
print(reminders)
Output:
Reminder: Your appointment is tomorrow.
Code:
#Example-1
item = "bananas"
if item in shopping_list:
else:
Output:
bananas is on the shopping list.
#Example-2
if book in library_catalog:
else:
Output:
Machine Learning is available for borrowing.
#Example-3
person = "Charlie"
if person in event_attendees:
else:
Output:
Charlie is attending the event.
#Example-4
email = "[email protected]"
if email in approved_emails:
else:
Output:
[email protected] is an approved email address.
#Example-5
product = "Laptops"
if product in warehouse_inventory:
print(f"{product} is in stock.")
else:
Output:
Laptops is in stock.
List Slicing and Copying:
Slicing to create sublists
Slicing is a way to create sublists from a larger list by specifying a range of indices
It doesn't modify the original list.
Code:
#Example-1
slice_of_pizza = pizza[1:3]
slice_of_pizza
Output:
['pepperoni', 'vegetarian']
#Example-2
selected_pages = book[20:30]
selected_pages
Output:
['song2', 'song3', 'song4']
#Example-4
shopping_list = supermarket[2:4]
shopping_list
Output:
['meat', 'canned goods']
#Example-5
work_hours = hours_of_day[9:17]
work_hours
Output:
Creating a shallow copy of a list creates a new list, but the elements themselves are still references to the
original elements
Creating a deep copy creates a completely independent duplicate of the list and its elements.
Code:
#Exapmle-1
book. The pages are the same as the original book, but if you
import copy
photocopy = copy.copy(original_book)
photocopy.append("Page 4")
photocopy
Output:
#Example-2
import copy
duplicate_painting = copy.deepcopy(original_painting)
duplicate_painting["color"] = "red"
duplicate_painting
Output:
#Example-3
someone. Both you and the other person have access to the same
list of addresses. If they add a new address, you can see it too.
import copy
friend_address_book = your_address_book
friend_address_book.append("David")
friend_address_book
Output:
#Example-4
animal that looks and acts like the original. Any changes made to
import copy
cloned_pet = copy.deepcopy(original_pet)
cloned_pet["name"] = "Buddy"
cloned_pet
Output:
#Example-5
with a friend. You both have access to the same set of photos. If
your friend deletes a photo, it's also gone from your collection.
import copy
friend_photos = your_photos
del friend_photos[1]
friend_photos
Output:
['Photo1.jpg', 'Photo3.jpg']
List Sorting
Python provides several methods for sorting lists, the most common being the sort() method and the
sorted() function.
For instance, to sort a list of strings by their lengths, you can use the len function as the key
To sort a list in descending order, you can use the reverse parameter or the ‘reverse()’ method.
Code:
#Example- 1
students.sort(key=lambda x: x[1])
print(students)
Output:
#Example-2
alphabetical order.
"Data Science"]
sorted_books = sorted(books)
print(sorted_books)
Output:
#Example-3
2009)]
movies.sort(key=lambda x: x[1])
print(movies)
Output:
#Example- 4
best deals.
products = [
products.sort(key=lambda x: x["price"])
print(products)
Output:
[{'name': 'Tablet', 'price': 300}, {'name': 'Smartphone', 'price': 600}, {'name': 'Laptop', 'price': 800}]
#Example- 5
level. You can sort the list based on the priority to tackle
tasks = [
tasks.sort(key=lambda x: x["priority"])
print(tasks)
Output:
[{'task': 'Finish project', 'priority': 1}, {'task': 'Buy groceries', 'priority': 2}, {'task': 'Read a book', 'priority': 3}]
List Sorting
List indexing allows you to access individual elements of a list using their positions (indices).
The first element has an index of 0, the second has an index of 1, and so on
Python also supports negative indexing, which allows you to access elements from the end of the list. -1
Code:
#Example-1
item on the shelf has an index. You can grab an item from the
selected_item = supermarket_shelf[2]
print(selected_item)
Output:
oranges
#Example-2
"Conclusion"]
current_page = book_pages[3]
print(current_page)
Output:
Conclusion
#Example-3
now_playing = playlist[1]
print(now_playing)
Output:
Song 2
#Example-4
open_file = folder_files[2]
print(open_file)
Output:
data.csv
#Example-5
needed_ingredient = recipe_ingredients[0]
print(needed_ingredient)
Output:
Flour
What is Stack?
Code:
#Example-1
stack_of_plates = []
stack_of_plates.append("Plate 1")
stack_of_plates.append("Plate 2")
stack_of_plates.append("Plate 3")
Output:
#Example-2
browsing_history = []
browsing_history.append("Homepage")
browsing_history.append("About Us")
browsing_history.append("Contact Us")
last_page_visited = browsing_history.pop()
#Example-3
undo_stack = []
undo_stack.append("Typed 'Hello'")
Output:
#Example-4
def function_a():
print("Function A")
def function_b():
print("Function B")
function_a()
function_b()
Output:
Function A
Function B
#Example-5
#Analogy: When dealing with a deck of cards, the last card placed
deck_of_cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9",
top_card = deck_of_cards.pop()
print(top_card)
Output:
King
Push: The "push" operation is used to add an element to the top of the stack. When you push an element
Pop: The "pop" operation is used to remove the top element from the stack. After a pop operation, the
element just below the top becomes the new top element.
Code:
#Example-1
to the top and remove them from the top, just like in a stack
data structure.
stack_of_plates.append("Plate 1")
stack_of_plates.append("Plate 2")
stack_of_plates.append("Plate 3")
popped_plate = stack_of_plates.pop()
Output:
#Example-2
webpage onto a stack. When you click the "Back" button, it's like
history_stack.append("Homepage")
history_stack.append("Page 1")
previous_page = history_stack.pop()
Output:
#Example-3
function onto the call stack. When the function returns, it's
def foo():
print("Inside foo")
def bag():
print("Inside bag")
bag() # Call the bar function, pushing functions onto the call
stack
Output:
Inside bag
Inside foo
#Example-4
that edit onto the undo stack. When you press "Undo," it's like
print("Undo:", text)
Output:
#Example-5
customer
print("Served:", served_customer)
Output:
Served: Customer 1
Queue
A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. This means that the first
Queues are used to manage and process items in an orderly, sequential manner.
Properties of Queues:
FIFO Principle: The most fundamental property of a queue is its adherence to the FIFO principle. This ensures
that the item that has been in the queue the longest is the first to be processed
Two Ends: A queue typically has two ends: the front and the rear. New elements are enqueued (added) at
the rear, and elements are dequeued (removed) from the front
Sequential Processing: Queues are designed for sequential processing. Items are processed one after the
#Example-1
served.
checkout_queue = deque()
checkout_queue.append("Customer 1")
checkout_queue.append("Customer 2")
checkout_queue.append("Customer 3")
while checkout_queue:
customer = checkout_queue.popleft()
print(f"Serving {customer}")
Output:
Serving Customer 1
Serving Customer 2
Serving Customer 3
#Example-2
#Analogy: In a printer, print jobs are queued up, and the first
print_queue = Queue()
print_job = print_queue.get()
print(f"Printing: {print_job}")
Output:
#Example-3
task_queue = Queue()
task_queue.put("Task 1")
task_queue.put("Task 2")
task_queue.put("Task 3")
task = task_queue.get()
Output:
Executing task: Task 1
#Example-4
call_queue = Queue()
call_queue.put("Customer 1")
call_queue.put("Customer 2")
call_queue.put("Customer 3")
customer = call_queue.get()
Output:
Assisting customer: Customer 1
message_queue = Queue()
message_queue.put("Message 1")
message_queue.put("Message 2")
message_queue.put("Message 3")
message = message_queue.get()
Output:
Processing message: Message 1
doubled_prices
Output:
[20, 40, 60, 80, 100]
#Example-2
capitalized_names
Output:
['Arun', 'Bob', 'Chals', 'Dave']
#Example-3
numbers = [1, 2, 3, 4, 5]
squares
Output:
[1, 4, 9, 16, 25]
#Example-4
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_numbers
Output:
[1, 3, 5, 7, 9]
#Example-5
#Analogy: Suppose you have a list of file names, and you want to
extract the file extensions from them.
extensions
Output:
Conditional list comprehensions allow you to filter and transform data within a list comprehension based on
specified conditions.
Code:
#Example-1
Passed_students
Output:
#Example-2
product['category'] == 'Electronics']
electronics
Output:
['Laptop']
#Example-3
'[email protected]', '[email protected]']
email.endswith('@example.com')]
example_emails
Output:
['[email protected]', '[email protected]']
#Example- 4
even_numbers
Output:
[12, 6, 14, 8]
#Example-5
keyword = 'Python'
keyword in article]
relevant_articles
Output:
Nested list comprehensions allow you to create lists of lists and perform operations on nested data
structures.
Code:
#Example-1
result
Output:
#Example-2
translated_points
Output:
items
Output:
['apple', 'banana', 'cherry', 'dog', 'elephant', 'car', 'bus', 'bike']
#Example-4
csv_data = [
names
Output:
['Arun', 'Bob', 'Chals']
#Example-5
students = [
['David', 'Chemistry', 5]
senior_courses
Output:
['Math', 'Chemistry']
Advantages of List Comprehensions
A list comprehension is a concise way to create lists in Python. Here's a more detailed explanation of the
advantages of list comprehension
Readability: List comprehensions are often more readable and intuitive than traditional for loops,
especially for simple operations. They express the intended operation directly
Conciseness: List comprehensions allow you to achieve the same result with fewer lines of code. This
reduces code clutter and makes your code more compact
Performance: List comprehensions are generally faster than traditional for loops because they are
optimized for performance by Python's interpreter
Expressiveness: List comprehensions promote a more functional style of programming in Python,
allowing you to map, filter, and transform data in a clear and expressive manner
Reduced Bugs: With list comprehensions, there are fewer chances for off-by-one errors or other common
loop-related bugs, as the structure is more straightforward.
Tuples
Introduction to Tuples
Tuples are ordered collections of elements, often heterogeneous, enclosed within parentheses.
They are immutable, meaning once created, their elements cannot be changed
Tuples are created using parentheses ‘()’ and separating elements with commas ‘,’.
# Example Tuple.
tuplee = ('pw','skills',1,2,'pwioi')
print(tuplee)
O utput:
Example
#Example-1
current_page = book_pages[2]
#Example-2
'Vanilla')
required_ingredients = recipe_ingredients[1:4]
Output:
#Example-4
Measure')
'Wrench', 'Pliers'
Output:
#Example-5
current_song = playlist[2]
favourite_songs = playlist[1:4]
Output:
Code:
#Example-1
apple_count = inventory.count('Apple')
Output:
#Example-2
first_A_index = grades.index('A')
Output:
#Example-3
Output:
Total expenses for both months: (1000, 1200, 800, 1100, 1300, 850)
#Example-4
#Analogy: Coordinates
#Example-5
extended_menu = menu_options * 2
Output:
Sets
Introductio
They don't allow duplicate elements and are represented by curly braces {} in Python
Example code:
#Example
my_set = {1, 2, 3}
print(my_set)
print(another_set)
Output:
{1, 2, 3}
{3, 4, 5}
Set Methods
remove(): Removes a specific element from the set. Raises an error if the element doesn’t exist
discard(): Removes a specific element from the set if it exists. Doesn't raise an error if the element is not
present
#Example-1
#Analogy: Suppose you have two shopping carts with items, and you
want to find out what items are common in both carts.
common_items = cart1.intersection(cart2)
Output:
Common items: {'grapes', 'banana'}
#Example-2
common_courses = courses_offered.intersection(my_courses)
Output:
Common courses: {'Chemistry', 'Biology'}
#Example-3
unique_skills_employee1 =
employee1_skills.difference(employee2_skills)
unique_skills_employee2 =
employee2_skills.difference(employee1_skills)
Output:
Employee 1 unique skills: {'SQL', 'C++'}
#Example-4
mutual_friends = facebook_friends.intersection(twitter_friends)
Output:
Mutual friends: {'Alice', 'Charlie'}
#Example-5
missing_ingredients =
required_ingredients.difference(available_ingredients)
Output:
Missing ingredients: {'vanilla', 'butter'}
Set Operations
Union (|): Combines elements from two sets, excluding duplicates
Intersection (&): Finds common elements between sets
Difference (-): Returns elements that are in the first set but not in the second
Symmetric Difference (^): Returns elements that are in either of the sets, but not in both.
Code:
#Example-1
Output:
Common interests: {'coding'}
#Example-2
Output:
Courses available for both students: {'Physics'}
#Example-3
Output:
Common items in shopping lists: {'bread', 'milk'}
#Example-4
Output:
Common skills between departments: {'analytics'}
#Example-5
Dictionary
Introduction to dictionarie
Dictionaries are a data structure in Python that store data as key-value pairs.
They are unordered collections and are defined using curly braces {}. Keys are unique and immutable,
Keys are unique and immutable, while values can be of any data type
Elements are accessed by referencing their keys using square brackets [].
Advance Dictionary
Sorting Dictionaries
Dictionaries cannot be sorted directly, but they can be sorted based on keys or values using functions like
Nested Dictionaries
These nested dictionaries can be accessed and manipulated just like any other dictionary
Removing Elements
pop(): Removes and returns the value associated with the specified key
popitem(): Removes and returns the last inserted key-value pair as a tuple.
Code:
#Example-1
related information.
library_catalog = {
'genre': 'Fiction'},
'Finance'}
book_id = 102
print(f"Book '{library_catalog[book_id]['title']}' by
{library_catalog[book_id]['author']} is in the
{library_catalog[book_id]['genre']} genre.")
Output:
#Example-2
subjects.
student_database = {
'Science', 'English']},
'Geography', 'Math']}
student_id = 'S001'
{student_database[student_id]['grade']}.")
'.join(student_database[student_id]['subjects'])} subjects.")
Output:
#Example-3
categories.
product_inventory = {
'category': 'Electronics'},
'category': 'Accessories'},
product_id = 'P002'
print(f"Product '{product_inventory[product_id]['name']}' is in
${product_inventory[product_id]['price']}.")
Output:
employee_records = {
employee_id = 'E001'
print(f"{employee_records[employee_id]['name']}'s salary is
${employee_records[employee_id]['salary']}.")
Output:
John Doe works in the Engineering department.
#Example-5
restaurant_menu = {
dish_name = 'Dish3'
print(f"'{restaurant_menu[dish_name]['name']}' costs
${restaurant_menu[dish_name]['price']}.")
print(f"Description: {restaurant_menu[dish_name]
['description']}")
Output:
'Margherita Pizza' costs $14.0.
Conciseness and readability: They provide a more compact and readable way to create dictionaries
compared to traditional methods like loops or for loops combined with if statements
Expressiveness: Dictionary comprehensions allow developers to express complex operations in a succinct
manner, enhancing code clarity and maintainability
Efficiency: They often result in faster execution times and better performance, especially for smaller
dictionaries.
Real-time Analogy
Code:
#Example-1
print(grade_dict)
Output:
{'Arun': 85, 'Bob': 92, 'Charlie': 78}
#Example-2
print(char_count)
Output:
{'H': 1, 'e': 5, 'l': 5, 'o': 4, ',': 1, 'E': 1, 'v': 1, 'r': 1, 'y': 1, 'n': 1, 'W': 2, 'c': 1, 'm': 1, 't': 1, 'P': 1, 's': 2, 'k': 1, 'i': 1}
#Example-3
30}
in celsius_temperatures.items()}
print(fahrenheit_temperatures)
Output:
#Example-4
dictionary comprehension
zip(usernames, user_ids)}
print(user_id_mapping)
Output:
#Example-5
counts as values.
word = 'encyclopedia'
char.lower() in 'aeiou'}
print(vowel_count)
Output:
In Python, dictionary view objects provide dynamic, live views of a dictionary's contents. These views reflect
They offer an interface to observe and interact with the keys, values, or key-value pairs within a dictionary
One crucial aspect of dictionary views is their dynamic nature. They are live representations of the original
dictionary, meaning they reflect any changes made to the underlying dictionary in real time.
If the dictionary changes (keys, values, or items are added, modified, or removed), these changes are
dict.keys(): This method returns a view object that displays all the keys present in the dictionary. It
represents the keys as a set-like object, providing operations like membership tests (e.g., in operator) and
dict.values(): The values() method returns a view object that shows all the values present in the dictionary.
Similar to dict.keys(), this view represents the values as a set-like object, allowing operations like iteration
dict.items(): The items() method returns a view object that displays all the key-value pairs present in the
dictionary. Each item in the view is a tuple containing a key-value pair. This view is iterable and allows
Analogy Code:
#Example-1
library_books = {
book_ids_view = library_books.keys()
Output:
#Example-2
book_titles_view = library_books.values()
Output:
Book Title: Introduction to Python
#Example-3
book_id_title_view = library_books.items()
Output:
Book ID: 101 - Book Title: Introduction to Python
#Example-4
recipe = {
'eggs': '2',
ingredients_view = recipe.keys()
print(f"Ingredient: {ingredient}")
Output:
Ingredient: flour
Ingredient: sugar
Ingredient: eggs
Ingredient: milk
#Example-5
quantities_view = recipe.values()
print(f"Quantity: {quantity}")
Output:
Quantity: 2 cups
Quantity: 1 cup
Quantity: 2