Python
Python
A dictionary is a collection of key-value pairs. dictionaries are defined with curly braces {}
Creating a Dictionary
We can create a dictionary by placing key-value pairs inside curly braces {}, separated by
colons :.
# Example of a simple dictionary
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
Accessing Values
can access values by referencing the key inside square brackets [] or using the get()
method.
# Accessing values
print(my_dict["name"]) # Output: Alice
print(my_dict.get("age")) # Output: 30
Modifying a Dictionary
You can add or modify key-value pairs.
# Modifying values
my_dict["age"] = 31 # Updates the age
my_dict["email"] = "alice@example.com" # Adds a new key-value pair
Built In Functions used on Dictionaries
Python provides several built-in functions and methods that can be used with dictionaries.
1. len()
Returns the number of key-value pairs in the dictionary.
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(len(my_dict)) # Output: 3
2. dict()
Creates a new dictionary. can create dictionaries in several ways using the dict() function.
# Creating an empty dictionary
new_dict = dict()
print(new_dict) # Output: {}
# Creating a dictionary from key-value pairs
new_dict = dict(name="Alice", age=30)
print(new_dict) # Output: {'name': 'Alice', 'age': 30}
# Creating a dictionary from a list of tuples
new_dict = dict([("name", "Alice"), ("age", 30)])
print(new_dict) # Output: {'name': 'Alice', 'age': 30}
3. keys()
Returns a view object that displays a list of all the keys in the dictionary.
my_dict = {"name": "Alice", "age": 30}
keys = my_dict.keys()
print(keys) # Output: dict_keys(['name', 'age'])
4. values()
Returns a view object that displays a list of all the values in the dictionary.
values = my_dict.values()
print(values) # Output: dict_values(['Alice', 30])
5. items()
Returns a view object that contains a list of the dictionary’s key-value pairs as tuples.
items = my_dict.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 30)])
6. get()
Returns the value of a specified key. If the key does not exist, it returns None or a default
value.
# Existing key
print(my_dict.get("name")) # Output: Alice
# Non-existent key
print(my_dict.get("city", "Not found")) # Output: Not found
7. pop()
Removes a key-value pair from the dictionary and returns the value. If the key does not exist,
it raises a KeyError.
# Removing an existing key
age = my_dict.pop("age")
print(age) # Output: 30
print(my_dict) # Output: {'name': 'Alice'}
8. popitem()
Removes and returns the last inserted key-value pair as a tuple. If the dictionary is empty, it
raises a KeyError.
# Using popitem
last_item = my_dict.popitem()
print(last_item) # Output: ('name', 'Alice')
9. update()
Updates the dictionary with elements from another dictionary or an iterable of key-value
pairs.
python
my_dict = {"name": "Alice", "age": 30}
3. fromkeys()
Creates a new dictionary with keys from a sequence and sets all values to a specified value
(or None by default).
4. get()
Returns the value for the specified key. If the key doesn’t exist, it returns None or a specified
default value.
5. items()
Returns a view object of the dictionary's key-value pairs as tuples.
6. keys()
Returns a view object containing the dictionary's keys.
7. pop()
Removes the specified key and returns the associated value. If the key is not found, it raises
a KeyError. You can also provide a default value to avoid the error.
10. update()
Updates the dictionary with key-value pairs from another dictionary or an iterable of key-
value pairs. If a key already exists, its value is updated; if a key does not exist, it's added.
Method Description
clear() Removes all elements from the dictionary.
copy() Returns a shallow copy of the dictionary.
fromkeys() Creates a new dictionary with keys from a sequence and a specified value.
get() Returns the value for the specified key, or a default value.
items() Returns a view object of the dictionary’s key-value pairs.
keys() Returns a view object of the dictionary’s keys.
pop() Removes and returns the value for the specified key.
popitem() Removes and returns the last inserted key-value pair.
setdefault() Returns the value of a key, or sets it to a default if missing.
update() Updates the dictionary with key-value pairs from another dictionary or iterable.
values() Returns a view object of the dictionary’s values.
Del statement
The del statement in Python is used to delete objects. It can be used to remove elements
from lists or dictionaries, delete variables, or even delete slices from a list.
Syntax:
del object
Use Cases of del in Python
1. Deleting a Dictionary Key-Value Pair: You can use del to remove a specific key-value
pair from a dictionary.
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
del my_dict["age"] # Deletes the key 'age'
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
Deleting Variables: The del statement can delete a variable, which means that the variable
will no longer exist.
x = 10
del x
# print(x) # This will raise a NameError because x is deleted
Deleting Elements from a List: You can remove an element at a specific index in a list using
del.
my_list = [1, 2, 3, 4, 5]
del my_list[2] # Deletes the element at index 2
print(my_list) # Output: [1, 2, 4, 5]
Deleting a Slice from a List: You can delete multiple elements by specifying a slice.
my_list = [1, 2, 3, 4, 5]
del my_list[1:3] # Deletes elements from index 1 to 2 (slicing)
print(my_list) # Output: [1, 4, 5]
Deleting Objects: You can use del to delete an entire object, such as a list, dictionary, or class
instance.
my_list = [1, 2, 3]
del my_list
# print(my_list) # Raises NameError as my_list no longer exists
Tuples and Sets :
Tuples in Python
A tuple is an immutable, ordered sequence of elements. Unlike lists, the elements in a tuple
cannot be modified (added, removed, or changed) after it is created. Tuples are commonly
used to store collections of items that should not change.
Creating Tuples
You can create a tuple by enclosing elements in parentheses () separated by commas.
Ways to Create Tuples in Python
1. Creating a Tuple with Multiple Elements: You can create a tuple by placing elements
inside parentheses and separating them with commas.
# Tuple with integers
my_tuple = (1, 2, 3, 4)
print(my_tuple) # Output: (1, 2, 3, 4)
# Indexing
print(my_tuple[0]) # Output: 10
print(my_tuple[-1]) # Output: 60
# Slicing
print(my_tuple[1:4]) # Output: (20, 30, 40)
print(my_tuple[:3]) # Output: (10, 20, 30)
print(my_tuple[2:]) # Output: (30, 40, 50, 60)
print(my_tuple[::2]) # Output: (10, 30, 50)
print(my_tuple[::-1]) # Output: (60, 50, 40, 30, 20, 10) # Reversing tuple
Built in functions used on Tuples :
Python provides several built-in functions that can be used to perform operations on tuples.
Here are some commonly used built-in functions for tuples:
1. len()
The len() function returns the number of elements in the tuple.
my_tuple = (10, 20, 30, 40)
print(len(my_tuple)) # Output: 4
2. max()
The max() function returns the largest element in the tuple. All elements in the tuple must
be comparable.
my_tuple = (10, 20, 30, 40)
print(max(my_tuple)) # Output: 40
3. min()
The min() function returns the smallest element in the tuple.
my_tuple = (10, 20, 30, 40)
print(min(my_tuple)) # Output: 10
4. sum()
The sum() function returns the sum of all elements in the tuple. All elements must be
numeric.
my_tuple = (10, 20, 30)
print(sum(my_tuple)) # Output: 60
Relation Between Tuples and Lists
Tuples and lists in Python are both sequences used to store collections of items, but they
have key differences and similarities.
Similarities Between Tuples and Lists:
1. Ordered: Both tuples and lists are ordered collections. This means that elements
have a defined sequence and can be accessed using their index (starting from 0).
o
my_list = [10, 20, 30]
my_tuple = (10, 20, 30)
print(my_list[1]) # Output: 20
print(my_tuple[1]) # Output: 20
Indexing and Slicing: Both lists and tuples support indexing and slicing operations to access
elements or subsets of elements.
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)
print(my_list[2:4]) # Output: [3, 4]
print(my_tuple[2:4]) # Output: (3, 4)
Differences Between Tuples and Lists:
Feature Lists Tuples
Lists are mutable (you can
Tuples are immutable (you cannot change
Mutability change, add, or remove
or modify elements once defined).
elements).
Syntax Defined using square brackets []. Defined using parentheses ().
Slightly slower due to mutability Faster than lists because of immutability
Performance
and additional memory usage. (less memory overhead).
Ideal when you need to modify
Ideal for read-only or constant data where
Use Cases the collection (adding, removing,
no modifications are needed.
or updating elements).
Memory Lists consume more memory due Tuples consume less memory because
Usage to the ability to grow and shrink. they are fixed in size.
Lists have more built-in methods
Methods Tuples have fewer methods (only count()
like append(), remove(), and
Available and index() are available).
pop().
Lists are not hashable, so they Tuples are hashable (if they contain only
Hashability cannot be used as dictionary immutable elements), so they can be used
keys or elements in sets. as dictionary keys and in sets.