0% found this document useful (0 votes)
7 views15 pages

Python Dictionaries and Functions Guide

The document provides an overview of dictionaries and functions in Python, detailing their properties, methods, and usage. It explains how to access, update, and delete dictionary elements, as well as the syntax and types of functions, including recursion. Additionally, it addresses common questions regarding dictionaries and functions, offering examples and explanations for better understanding.

Uploaded by

prachi.bca
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views15 pages

Python Dictionaries and Functions Guide

The document provides an overview of dictionaries and functions in Python, detailing their properties, methods, and usage. It explains how to access, update, and delete dictionary elements, as well as the syntax and types of functions, including recursion. Additionally, it addresses common questions regarding dictionaries and functions, offering examples and explanations for better understanding.

Uploaded by

prachi.bca
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Apollo Institute of Professional studies, Kanpur (2025-26)

UNIT-III

Dictionary and Function

BY- PRACHI KUSHWAHA

What is a Dictionary?
• A dictionary is an unordered collection of key-value pairs.
• Each key is unique and immutable (like strings, numbers, tuples), while values
can be of any data type.
• Dictionaries are mutable, meaning you can change, add, or remove elements.
Syntax:
my_dict = {
"key1": "value1",
"key2": "value2",
"key3": 3
}

1. Accessing Values in a Dictionary


A dictionary stores data in key-value pairs. To get a value:
my_dict = {'name': 'Alice', 'age': 25}

# Access using key


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

# Using get() method (safer, avoids KeyError)


print(my_dict.get('age')) # Output: 25
2. Updating a Dictionary
You can change existing values or add new key-value pairs:
# Updating existing key
my_dict['age'] = 26

# Adding new key-value


my_dict['city'] = 'New York'

print(my_dict)
# Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
• You can also use .update() method:
my_dict.update({'age': 27, 'country': 'USA'})

3. Deleting Dictionary Elements


Remove items using:
# Remove a key-value pair
del my_dict['city']

# Remove and return value


age = my_dict.pop('age')

# Remove all items


my_dict.clear()

# Delete entire dictionary


del my_dict
Properties of Dictionary Keys
• Keys must be immutable (e.g., string, number, tuple).
• Keys must be unique.
• Values can be any data type.

Built-in Dictionary Methods

Method Description

keys() Returns all keys

values() Returns all values

items() Returns key-value pairs

get(key) Returns value for key safely

update(dict) Updates dictionary with another dictionary

pop(key) Removes key and returns value

clear() Removes all items

copy() Returns a shallow copy

setdefault(key, default) Returns value; if key not found, inserts key with default value

Function in Python
A function in Python is a block of reusable code that performs a specific task.
It helps make programs shorter, easier to read, and easier to debug.
Why use functions?
• Avoid writing the same code multiple times
• Make code organized and modular
• Easier to test and maintain

Syntax of a Function
Example 1: Simple Function
def greet():
print("Hello, welcome to Python!")

greet() # function call


Output: Hello, welcome to Python!
Function with Parameters
def add(a, b):
return a + b

result = add(5, 3)
print("Sum:", result)
Output: Sum: 8
Calling a Function
Once defined, you call (or invoke) it using its name followed by parentheses.
Example:
greet() # Output: Hello, welcome!
Pass by Reference vs Pass by Value
In Python:
• Immutable data types (like int, float, string, tuple) behave like pass by value →
changes inside the function don’t affect the original.
• Mutable data types (like list, dict) behave like pass by reference → changes
inside the function affect the original object.
Example:

Function Arguments in Python


Function arguments are the values passed to a function when it is called.
They allow you to send information into a function.

Types of Function Arguments


[Link] Arguments
• Must be passed in the correct order and number.
• If any argument is missing → error occurs.
Example:
2,Keyword Arguments
• You can pass values using the parameter name.
• Order doesn’t matter.
Example:

[Link] Arguments
• You can assign a default value to a parameter.
• If no value is provided during the call, the default value is used.
Example:

Variable-Length Arguments
Used when number of arguments is unknown.
• *args → For non-keyword arguments (tuple form)
• **kwargs → For keyword arguments (dictionary form)
Example 1: Using *args
OUTPUT- 10
Example 2: Using **kwargs

Recursion in Python-
Recursion is a process where a function calls itself directly or indirectly to solve a
problem.
Each time the function calls itself, the problem becomes smaller, and there must be a
base condition to stop the recursion.
def function_name():
# some code
function_name() # function calling itself
Important Parts of Recursion
1. Base Case:
The condition where recursion stops. (prevents infinite loop)
2. Recursive Case:
The part where the function calls itself.

Example: Factorial Using Recursion


Advantages-
Makes code simple and clean for repetitive problems (like factorial, Fibonacci,
etc.)

Disadvantages-
• Uses more memory (each function call is stored in stack)
• May cause infinite recursion if base case is missing.

[Link] Series (using Recursion)-


Logic:
F(n) = F(n−1) + F(n−2)
Base cases: F(0) = 0, F(1) = 1
Example:
Sum of Natural Numbers (using Recursion)
Logic:
Sum(n) = n + Sum(n−1)
Base case: Sum(1) = 1
Example:
IMPORTANT QUESTIONS REGARDING EXAM-

Q1. What is a dictionary in Python?


Answer:
A dictionary in Python is an unordered, mutable, and indexed collection of key–value
pairs.
Each key must be unique and immutable, while values can be of any data type.
Example:
student = {"name": "Amit", "age": 20, "course": "Python"}

Q2. How do you access values in a dictionary?


Answer:
You can access values using the key name in square brackets or the get() method.
student = {"name": "Amit", "age": 20}
print(student["name"]) # Output: Amit
print([Link]("age")) # Output: 20
Q3. How can you update a dictionary?
Answer:
You can update an existing key’s value or add a new key–value pair.
student = {"name": "Amit", "age": 20}
student["age"] = 21 # Update existing key
student["city"] = "Delhi" # Add new key
print(student)

Q4. How to delete elements from a dictionary?


Answer:
• del keyword → deletes a specific key
• pop() → removes key and returns its value
• clear() → removes all items
• del dict → deletes entire dictionary
Example:
student = {"name": "Amit", "age": 20}
del student["age"]
[Link]("name")
[Link]()

Q5. What are the properties of dictionary keys?


Answer:
1. Keys must be unique.
2. Keys must be immutable (can be strings, numbers, or tuples).
3. A dictionary can contain different data types for values.
Q6. What are some built-in dictionary functions and methods?
Answer:

Function/Method Description Example

len() Returns number of items len(student)

str() Converts to string str(student)

keys() Returns all keys [Link]()

values() Returns all values [Link]()

items() Returns key-value pairs [Link]()

get(key) Returns value of key [Link]("name")

update(dict2) Adds or updates [Link]({"city":"Delhi"})

pop(key) Removes item [Link]("age")

clear() Clears dictionary [Link]()

Q7. What is a function in Python?


Answer:
A function is a block of reusable code that performs a specific task.
It helps to reduce code duplication and improve readability.
Syntax:
def function_name(parameters):
# function body
return value

Q8. How do you define and call a function in Python?


Answer:
def greet(name):
print("Hello,", name)
greet("Prachi") # Function call

Q9. Explain Pass by Value vs Pass by Reference in Python.


Answer:
• Pass by Value: The function gets a copy of the object (for immutable types like
int, string, tuple).
• Pass by Reference: The function gets a reference to the object (for mutable
types like list, dictionary).
Example:
def modify(lst):
[Link](100)

nums = [10, 20]


modify(nums)
print(nums) # Output: [10, 20, 100] (changed)

Q10. What are the types of function arguments in Python?


Answer:
1. Required arguments: Passed in correct order.
def add(a, b): print(a+b)
add(5, 10)
2. Keyword arguments: Passed using parameter names.
add(b=10, a=5)
3. Default arguments: Assigned default value if not provided.
def greet(name="User"): print("Hello", name)
greet() # Output: Hello User
4. Variable-length arguments:
o *args for variable number of positional arguments
o **kwargs for variable number of keyword arguments
def show(*args): print(args)
show(1,2,3) # Output: (1,2,3)
def display(**kwargs): print(kwargs)
display(name="Amit", age=20)
Q11. What is recursion?
Answer:
Recursion is a technique where a function calls itself repeatedly until a base condition
is met.
Example (Factorial):
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(5)) # Output: 120

Q12. Give examples of common recursion programs.

Program Description

Factorial n! = n * (n-1)!

Fibonacci Series Sum of previous two terms

Sum of Natural Numbers Recursively add numbers

Directory/Tree Traversal Used in file system operations

Example (Fibonacci):
def fib(n):
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2)

print(fib(6)) # Output: 8

You might also like