Basic Python For ML December 12 ,2024

 

1. Dictionaries: Key-Value Champions

1.1 What is a Dictionary?

A dictionary is a Python data structure that stores data as key-value pairs, where:

  • Keys: Unique and immutable (e.g., strings, numbers, or tuples).
  • Values: Can be any Python object, including lists, other dictionaries, or even functions.

Syntax

A dictionary is defined using curly braces {} or the dict() constructor.

# Creating a dictionary
my_dict = {"name": "Alice", "age": 25, "skills": ["Python", "ML"]}

# Using the dict() constructor
empty_dict = dict()
nested_dict = {"student": {"name": "Bob", "grade": "A"}}

1.2 Accessing and Modifying Dictionaries

Access Values

Use keys to retrieve values.

print(my_dict["name"])  # Output: Alice

To avoid errors, use the get() method for safe access:

print(my_dict.get("address", "Not Found"))  # Output: Not Found

Adding or Modifying Values

  • To add a new key-value pair:
my_dict["city"] = "New York"
  • To update an existing key’s value:
my_dict["age"] = 26

Deleting Entries

Remove key-value pairs using the del statement or the pop() method:

del my_dict["city"]  # Removes "city"
age = my_dict.pop("age")  # Removes "age" and returns its value

1.3 Looping Through a Dictionary

Loop Through Keys

for key in my_dict:
    print(key)

Loop Through Values

for value in my_dict.values():
    print(value)

Loop Through Key-Value Pairs

Use the items() method for unpacking key-value pairs:

for key, value in my_dict.items():
    print(f"{key}: {value}")

1.4 Common Dictionary Methods

MethodDescription
keys()Returns all the keys in the dictionary.
values()Returns all the values in the dictionary.
items()Returns all key-value pairs as tuples.
update()Updates the dictionary with key-value pairs from another dictionary.
clear()Removes all items from the dictionary.

1.5 When to Use Dictionaries

Dictionaries excel in scenarios requiring fast lookups or data organization:

  • Word Frequency Count: Count occurrences of words in text.
  • Configuration Management: Store settings for applications.
  • Mapping Relationships: Create JSON-like nested structures.

Example: Counting word occurrences.

text = "Python is easy to learn and powerful"
word_count = {}
for word in text.split():
    word_count[word] = word_count.get(word, 0) + 1
print(word_count)  # Output: {'Python': 1, 'is': 1, 'easy': 1, 'to': 1, 'learn': 1, 'and': 1, 'powerful': 1}

2. List Comprehensions: Pythonic and Efficient

2.1 What is a List Comprehension?

A list comprehension is a concise and expressive way to create lists in Python. It eliminates the need for verbose loops, making the code more readable and compact.

Syntax

[expression for item in iterable if condition]

Example

squared_numbers = [x**2 for x in range(5)]
print(squared_numbers)  # Output: [0, 1, 4, 9, 16]

2.2 Using Conditions in List Comprehensions

Add conditions to filter elements.

even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)  # Output: [0, 2, 4, 6, 8]

2.3 Nested List Comprehensions

List comprehensions can be nested to work with multi-dimensional data.

matrix = [[x for x in range(3)] for _ in range(3)]
print(matrix)  # Output: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

2.4 Practical Applications of List Comprehensions

1. Transform Data

Convert temperatures from Celsius to Fahrenheit:

celsius = [0, 20, 30]
fahrenheit = [((9/5)*temp + 32) for temp in celsius]
print(fahrenheit)  # Output: [32.0, 68.0, 86.0]

2. Filter Data

Extract positive numbers from a list:

numbers = [-5, 3, -1, 7]
positive_numbers = [num for num in numbers if num > 0]
print(positive_numbers)  # Output: [3, 7]

3. Flatten Nested Lists

Convert a 2D list into a 1D list:

nested_list = [[1, 2], [3, 4], [5]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)  # Output: [1, 2, 3, 4, 5]

3. Practical Applications of Python Data Structures

Data StructurePractical Use Case
ListsStore dynamic collections like a to-do list or inventory.
TuplesStore fixed data like coordinates or immutable records.
SetsRemove duplicates or find shared tags in a dataset.
DictionariesMap relationships, manage configurations, or count word occurrences.
List ComprehensionsQuickly filter or transform datasets during preprocessing.

Key Takeaways: Python Data Structures

1. Dictionaries: Key-Value Champions

  • Definition: Unordered collection of key-value pairs; keys are unique and immutable.
  • Syntax: my_dict = {"key": "value"} or dict().
  • Access/Modify: Use my_dict["key"] or my_dict.get("key", default).
  • Add/Update: my_dict["new_key"] = value.
  • Delete: del my_dict["key"] or my_dict.pop("key").
  • Iterate: Use keys(), values(), or items() for keys, values, and pairs.
  • Applications: Word counts, nested structures, fast lookups.

2. List Comprehensions: Pythonic and Efficient

  • Definition: Concise syntax for creating lists.
  • Syntax: [expression for item in iterable if condition].
  • Use Cases:
    • Transform: Convert Celsius to Fahrenheit.
    • Filter: Extract positives: [x for x in numbers if x > 0].
    • Flatten: flat_list = [item for sublist in nested_list for item in sublist].
  • Advantages: Readable, concise, efficient.

3. Practical Use Cases by Data Structure

  • Lists: Dynamic collections like to-do lists.
  • Tuples: Immutable data (e.g., coordinates).
  • Sets: Remove duplicates or compare datasets.
  • Dictionaries: Manage configurations or count occurrences.
  • List Comprehensions: Efficient data filtering or transformation.

 

Next Topic : File Handling in Python

 

Purnima
0

You must logged in to post comments.

Get In Touch

123 Street, New York, USA

+012 345 67890

techiefreak87@gmail.com

© Design & Developed by HW Infotech