Unit 3: Dictionaries & Functions



Dictionaries in Python

A dictionary is a collection of key–value pairs, where each key is used to access its value.

Key Characteristics

  • Unordered collection (in concept)
  • Mutable (can be changed)
  • Keys must be unique
  • Values can be duplicated
  • Written using curly braces {}

Example

student = { "roll": 101, "name": "Jay", "marks": 85 }

Dictionary Structure (Diagram)

Key → Value ------------------- "roll"101 "name""Jay" "marks"85

Accessing Values in Dictionary

Using Key Name

print(student["name"])

⚠ If key does not exist, it gives error.

Using get() Method (Safe Way)

print(student.get("marks"))

If key not found, it returns None instead of error.

Working with Dictionaries

Adding New Elements

student["age"] = 22

Updating Existing Value

student["marks"] = 90

Deleting Elements

del student["roll"] student.pop("age")

Looping Through Dictionary

for key in student: print(key, student[key])

Accessing Keys, Values, Items

print(student.keys()) print(student.values()) print(student.items())

Properties of Dictionary

PropertyDescription
MutableValues can be changed
Unique KeysNo duplicate keys
Indexed by KeyNot by position
DynamicCan grow or shrink
NestedCan contain dictionary inside dictionary

Nested Dictionary Example

emp = { "id": 1, "info": {"name": "Amit", "salary": 50000} }

Dictionary Functions

FunctionDescriptionExample
len()Number of key-value pairslen(student)
type()Type of variabletype(student)
str()Convert to stringstr(student)

Important Dictionary Methods

Commonly Used Methods

MethodPurpose
get()Get value
keys()All keys
values()All values
items()Key-value pairs
update()Update dictionary
pop()Remove key
clear()Remove all
copy()Copy dictionary

Example: student.update({"city": "Lucknow"})

Dictionary vs List (Exam Favorite)

FeatureDictionaryList
Data TypeKey-ValueIndex-Value
AccessBy keyBy index
Duplicate KeysNot allowedAllowed
OrderNo indexIndexed

Important Exam Points

  • Dictionary stores data in key-value form
  • Keys must be immutable (string, number, tuple)
  • Accessing non-existing key using [] gives error
  • get() method is safer than []
  • Dictionary is mutable

Frequently Asked Exam Questions

  • Define dictionary with example
  • Difference between list and dictionary
  • Explain dictionary methods
  • What is nested dictionary?

Functions in Python

A function is a block of reusable code that performs a specific task.
Instead of writing the same code again and again, we define it once and call it whenever needed.

Advantages of Functions

  • Code reusability
  • Better readability
  • Easy debugging
  • Modular programming

Defining & Calling a Function

Syntax to Define a Function

def function_name(parameters): statements return value

Example

def add(a, b): return a + b

Calling a Function

result = add(10, 20) print(result)

Passing Arguments to Functions

Arguments are values passed to a function during function call.

Example

def greet(name): print("Hello", name) greet("Jay")

Mutable & Immutable Data Types

Meaning

  • Mutable: Can be changed
  • Immutable: Cannot be changed

Common Examples

MutableImmutable
listint
dictionaryfloat
setstring
bytearraytuple

Effect on Function (Very Important for Exam)

Immutable Example

def change(x): x = x + 10 a = 5 change(a) print(a) # 5 (No change)

Mutable Example

def modify(lst): lst.append(4) my_list = [1, 2, 3] modify(my_list) print(my_list) # [1, 2, 3, 4]

Conclusion: Mutable objects are modified inside function, immutable are not.

Different Types of Arguments

1. Positional Arguments

Arguments passed in order.

def sub(a, b): print(a - b) sub(10, 5)

2. Keyword Arguments

Arguments passed using parameter name.

sub(b=5, a=10)

3. Default Arguments

Default value assigned to parameter.

def greet(name="User"): print("Hello", name) greet() greet("Jay")

4. Variable Length Arguments

*a) args (Non-keyword)

def total(*args): return sum(args) print(total(10, 20, 30))

**b) kwargs (Keyword arguments)

def info(**kwargs): print(kwargs) info(name="Jay", age=22)

Recursion

A function calling itself to solve a problem.

Two Parts of Recursion

  1. Base condition
  2. Recursive call

Example: Factorial

def fact(n): if n == 1: return 1 return n * fact(n-1) print(fact(5))

Recursion Flow Diagram (Text)

fact(5) → 5 * fact(4) → 4 * fact(3) → 3 * fact(2) → 2 * fact(1) → 1

Scope of Variables

Scope defines where a variable can be accessed.

Types of Scope

ScopeMeaning
LocalInside function
GlobalOutside function
Built-inPython predefined

Local Variable Example

def show(): x = 10 print(x)

Global Variable Example

x = 20 def display(): print(x)

Using global Keyword

x = 10 def change(): global x x = 50 change() print(x)

Exam-Oriented Important Points

  • Functions are defined using def keyword
  • Mutable arguments can be modified inside function
  • Immutable arguments remain unchanged
  • *args and **kwargs allow flexible arguments
  • Recursion must have base condition
  • Local variables have limited scope

Frequently Asked Exam Questions

  • Define function with example
  • Explain types of arguments
  • Difference between mutable and immutable
  • Explain recursion with example
  • Scope of variables in Python