Manu

Monday, 15 December 2025

Python Learning Session-10 : Dictionaries in Python –from lists, tuples and Key-Value Power!.

 

Session-10 : Dictionaries in Python –from lists, tuples and Key-Value Power!.

Learning Objectives

  • Understand what sets are in Python.
  • Learn how sets differ from lists and tuples.
  • Explore set operations (union, intersection, difference, symmetric difference).
  • Work with set methods like add(), remove(), discard(), update().
  • Understand immutability with frozenset.

πŸ“Œ Key Concepts

  1. Definition:
    A set is an unordered collection of unique elements in Python.
    Example:

Python

my_set = {1, 2, 3, 3} # Output: {1, 2, 3}

Show more lines

  1. Why Sets?
    • Automatically removes duplicates.
    • Faster membership testing (in operator).
    • Useful for mathematical operations.
  2. Creating Sets:

Python

s1 = {1, 2, 3}

s2 = set([4, 5, 6])

empty_set = set() # {} creates a dictionary, not a set

 

Show more lines

  1. Common Operations:

Python

a = {1, 2, 3}

b = {3, 4, 5}

 

print(a | b) # Union: {1, 2, 3, 4, 5}

print(a & b) # Intersection: {3}

print(a - b) # Difference: {1, 2}

print(a ^ b) # Symmetric Difference: {1, 2, 4, 5}

Show more lines

  1. Methods:
    • add(), remove(), discard(), pop(), clear()
    • update() for merging sets.
  2. frozenset:
    • Immutable version of a set.

Python

fs = frozenset([1, 2, 3])

Show more lines


πŸ›  Practice Ideas

  • Remove duplicates from a list using a set.
  • Find common elements between two lists.
  • Write a program to check if two sets are disjoint.
  • Implement a simple set-based membership system.

Key-Value Power


Learning Objectives

  • Understand what dictionaries are and why they are useful.
  • Learn how to create, access, and modify dictionary elements.
  • Explore dictionary methods like get(), keys(), values(), items(), update().
  • Understand nested dictionaries and dictionary comprehensions.

πŸ“Œ Key Concepts

  1. Definition:
    A dictionary is an unordered collection of key-value pairs.
    Example:

Python

my_dict = {"name": "Hitesh", "role": "Engineer"}

Show more lines

  1. Creating Dictionaries:

Python

d1 = {"a": 1, "b": 2}

d2 = dict(x=10, y=20)

empty_dict = {}

Show more lines

  1. Accessing & Modifying:

Python

print(d1["a"]) # 1

print(d1.get("c")) # None

d1["b"] = 5 # Modify value

d1["c"] = 3 # Add new key-value

Show more lines

  1. Common Methods:
    • keys(), values(), items()
    • update(), pop(), clear()
  2. Dictionary Comprehension:

Python

squares = {x: x**2 for x in range(5)}

Show more lines

  1. Nested Dictionaries:

Python

student = {

"name": "Hitesh",

"marks": {"math": 90, "science": 85}

 

Show more lines


πŸ›  Practice Ideas

  • Count word frequency in a sentence using a dictionary.
  • Merge two dictionaries.
  • Create a dictionary from two lists (keys and values).
  • Implement a simple phonebook using a dictionary.

 

No comments: