Dictionaries
In Python, a dictionary is a collection of key-value pairs, where each key is unique and associated with a value. Dictionaries are mutable, meaning they can be modified after creation. They are useful for storing and retrieving data in an associative manner, similar to a real-world dictionary.
Here's an example of a dictionary:
# Creating a dictionary
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# Accessing values in a dictionary
print("Name:", person["name"])
print("Age:", person["age"])
print("City:", person["city"])
# Modifying values in a dictionary
person["age"] = 35
print("Updated age:", person["age"])
# Adding new key-value pairs to a dictionary
person["occupation"] = "Engineer"
print("Occupation:", person["occupation"])
# Deleting a key-value pair from a dictionary
del person["city"]
print("Updated person:", person)
Output:
Name: John
Age: 30
City: New York
Updated age: 35
Occupation: Engineer
Updated person: {'name': 'John', 'age': 35, 'occupation': 'Engineer'}
In this example:
We create a dictionary
person
containing information about a person's name, age, and city.We access values in the dictionary using keys.
We modify values in the dictionary by assigning new values to keys.
We add new key-value pairs to the dictionary using assignment.
We delete a key-value pair from the dictionary using the
del
keyword.
Dictionaries provide a flexible way to store and manipulate data in Python, allowing for efficient lookup and modification of values based on keys.
Sample code
# We will interact with the GitHub API to get the list of pull requests
import requests
response = requests.get("https://api.github.com/repos/kubernetes/kubernetes/pulls")
# print(response.json())
# IMPORTANT: When you write response.json(), it automatically gets converted to a dictionary under the hood.
complete_details = response.json()
# To get details of one user only
# print(complete_details[2]["user"]["login"])
# To get the details of all the users
for i in range(len(complete_details)):
print(complete_details[i]["user"]["login"])
List of dictionaries
A list of dictionaries is a data structure in Python where each element in the list is a dictionary. This allows you to store a collection of related data items, where each item is represented as a dictionary with key-value pairs.
Here's a beginner-friendly example:
# Define a list of dictionaries representing information about students
students = [
{"name": "John", "age": 20, "grade": "A"},
{"name": "Alice", "age": 21, "grade": "B"},
{"name": "Bob", "age": 19, "grade": "C"},
]
# Iterate over the list of dictionaries and print information about each student
for student in students:
print(f"Name: {student['name']}, Age: {student['age']}, Grade: {student['grade']}")
Output:
Name: John, Age: 20, Grade: A
Name: Alice, Age: 21, Grade: B
Name: Bob, Age: 19, Grade: C
In this example:
We have a list called
students
, where each element is a dictionary representing information about a student.Each dictionary contains key-value pairs such as "name", "age", and "grade" for each student.
We iterate over the list using a
for
loop, and for each iteration, we access the dictionary representing a student.Inside the loop, we access specific keys in the dictionary (e.g., "name", "age", "grade") to print information about each student.
Lists of dictionaries are commonly used to represent structured data, such as records in a database, where each dictionary represents a record with multiple attributes or fields. They provide a flexible and convenient way to organize and manipulate data in Python.
Sets
In Python, a set is an unordered collection of unique elements. Sets are mutable, but they do not allow duplicate elements. They are useful for tasks such as eliminating duplicate elements from a list, performing set operations like union, intersection, and difference, and checking membership efficiently.
Here are some examples of sets in Python:
Example 1: Creating a Set
# Creating a set
my_set = {1, 2, 3, 4, 5}
print("Set:", my_set)
Output:
Set: {1, 2, 3, 4, 5}
Example 2: Adding Elements to a Set
# Creating an empty set
my_set = set()
# Adding elements to the set
my_set.add(1)
my_set.add(2)
my_set.add(3)
print("Updated Set:", my_set)
Output:
Updated Set: {1, 2, 3}
Example 3: Removing Elements from a Set
# Creating a set
my_set = {1, 2, 3, 4, 5}
# Removing elements from the set
my_set.remove(3)
my_set.discard(6) # No error if element doesn't exist
print("Updated Set:", my_set)
Output:
Updated Set: {1, 2, 4, 5}
Example 4: Set Operations
# Creating sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union of sets
union_set = set1.union(set2)
print("Union Set:", union_set)
# Intersection of sets
intersection_set = set1.intersection(set2)
print("Intersection Set:", intersection_set)
# Difference of sets
difference_set = set1.difference(set2)
print("Difference Set:", difference_set)
Output:
Union Set: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection Set: {4, 5}
Difference Set: {1, 2, 3}
Sets provide efficient methods for performing operations such as adding, removing, and performing set operations. They are particularly useful in scenarios where you need to work with unique elements or perform operations based on set theory.