Python Data Structures: Dictionaries, Strings, and Functions
Python Data Structures Fundamentals
Dictionaries: Key-Value Storage
A Python dictionary is a collection of key-value pairs used to store data in an unordered, mutable structure. You create a dictionary using curly braces {} with key-value pairs, for example: my_dict = {"name": "Alice", "age": 25}. You can also use the dict() constructor to create dictionaries.
Accessing values is done by referring to their keys: my_dict["name"] returns “Alice”.
Adding, Updating, and Removing Items
You add or update items by assigning a value to a key, such as my_dict["city"] = "New York" to add new or change existing entries. To remove items, use:
del my_dict["age"]pop("key")which removes and returns the value for the specified key.popitem()which removes and returns the last inserted key-value pair.
The clear() method empties the dictionary completely.
Essential Dictionary Methods
Dictionary methods provide powerful manipulation tools:
keys()returns all keys.values()returns all values.items()returns key-value pairs as tuples.get(key, default)safely accesses values and allows a default if the key is absent.
You can update one dictionary with another using update(), merging or overwriting existing keys. The copy() method returns a shallow copy of the dictionary. This flexibility makes dictionaries ideal for many programming tasks involving quick lookups, dynamic data storage, and key-based access to data.
Strings: Immutable Text Sequences
Strings in Python are sequences of characters used to store text data. They are immutable, meaning once created, their contents cannot be changed directly. However, you can perform numerous operations and use various built-in methods to manipulate and work with strings effectively.
For example, you can concatenate strings using the + operator or repeat them using the * operator: "hello " * 3 results in “hello hello hello “.
Common String Manipulation Methods
Common useful string methods include:
lower()andupper()to convert strings to lowercase or uppercase.strip()to remove whitespace from both ends.replace(old, new)to substitute parts of a string.split(delimiter)to split a string into a list based on a delimiter.join(list)to join a list of strings into one string.
For checking content, methods like isalpha() verify if all characters are letters, and isalnum() checks for alphanumeric characters. Searching within strings is facilitated by find() which returns the index of the first occurrence of a substring or -1 if not found.
String Method Examples
Examples:
text = "Hello World"
print(text.lower())
# Output: "hello world"
print(text.replace("World", "Everyone"))
# Output: "Hello Everyone"
words = text.split()
# Result: ['Hello', 'World']
joined = "-".join(words)
# Result: "Hello-World"
Functions: Reusable Code Blocks
Defining and Calling Functions
Python functions are reusable blocks of code defined using the def keyword followed by the function name and parentheses that may include parameters. For example:
def greet(name):
print(f"Hello, {name}!")
You can call this function with an argument to execute the code inside.
Function Arguments and Return Values
Functions can accept arbitrary arguments:
*argsto handle any number of positional arguments as a tuple.**kwargsto handle keyword arguments as a dictionary.
Default parameter values can be provided, which are used when no argument is passed for those parameters:
def greet(name="Guest"):
print(f"Hello, {name}!")
Functions can return values to the caller using the return statement. For example:
def add(a, b):
return a + b
Lambda Functions
Lambda functions are anonymous, concise functions defined with the lambda keyword, often used for short one-line functions:
square = lambda x: x * x
print(square(5))
# Output: 25
Arrays (Using the Array Module)
Arrays in Python, usually handled with the array module for fixed-type collections, allow looping through elements using a for loop:
import array
arr = array.array('i', [1, 2, 3])
for num in arr:
print(num)
Arrays support methods like append(), extend(), insert(), remove(), and pop() to manipulate elements similarly to lists but are more efficient for large numeric data.
