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

Lecture4 1

The document discusses nesting in Python dictionaries by providing examples of a list of dictionaries, a list in a dictionary, and a dictionary in a dictionary. It also covers defining functions, passing arguments to functions, returning values from functions, and passing lists and arbitrary arguments to functions.

Uploaded by

BasSem Reda
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 views29 pages

Lecture4 1

The document discusses nesting in Python dictionaries by providing examples of a list of dictionaries, a list in a dictionary, and a dictionary in a dictionary. It also covers defining functions, passing arguments to functions, returning values from functions, and passing lists and arbitrary arguments to functions.

Uploaded by

BasSem Reda
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
You are on page 1/ 29

Lecture 4

Python DICTIONARIES
Continue
10.Nesting
• Store multiple dictionaries in a list, or a list of Items as a value in a dictionary. This is called nesting.

•You can nest dictionaries inside a list, a list of items inside a dictionary, or even a dictionary inside
another dictionary. Nesting is a powerful feature

We will go through:

1. A List of Dictionaries.

2. A List in a Dictionary

3. A Dictionary in a Dictionary
10.Nesting
A List of Dictionaries.

It’s common to store a number of dictionaries in a list when each dictionary contains many kinds of
information about one object. For example: you might create a dictionary for each user on a website.

All of the dictionaries in the list should have an identical structure, so you can loop through the list and
work with each dictionary object in the same way.
10.Nesting
A List in a Dictionary.

Anytime you want more than one value to be associated with a single key in a dictionary, nest a list
inside a dictionary.
10.Nesting
A Dictionary in a Dictionary

For example, if you have several users for a website, each with a unique username, you can use the
usernames as the keys in a dictionary. You can then store information about each user by using a
dictionary as the value associated with their username.
Python Functions
Functions
Agenda

1. Defining a Function.
2. Passing Arguments.
3. Return Values.
4. Passing a List
5. Passing an Arbitrary Number of Arguments
6. Storing Your Functions in Modules
1. Defining a Function.
def greet_user():
"""Display a simple greeting."""
print("Hello!")
greet_user()

• The first line uses the keyword def to inform Python that you’re defining a function.
• In this case, the name of the function is greet_user(),
• It needs no information to do its job, so its parentheses are empty. (Even so, the
parentheses are required.)
• the definition ends in a colon.
• Any indented lines that follow def greet_user(): make up the body of the function.
• The text on the second line is a comment called a docstring, which describes what the
function does. These strings are usually enclosed in triple quotes, which lets you write
multiple lines.
• The line print("Hello!") is the only line of actual code in the body of this function,
• A function call tells Python to execute the code in the function. To call a function, you
write the name of the function, followed by any necessary information in parentheses.
1. Defining a Function.
Passing Information to a Function

By adding username here, you allow the function to accept any value of username you specify. The
function now expects you to provide a value for username each time you call it.
def greet_user(username):
"""Display a simple greeting."""
print(f"Hello, {username.title()}!")
greet_user(‘Adam’)
2. Passing Arguments
You can pass arguments to your functions in a number of ways.
You can use positional arguments, which need to be in the same order the parameters were
written; keyword arguments, where each argument consists of a variable name and a value; and
lists and dictionaries of values.
A. Positional Arguments
• Python must match each argument in the function call with a parameter in the function definition.
• The simplest way to do this is based on the order of the arguments provided.
• Values matched up this way are called positional arguments.
• Order Matters in Positional Arguments. You can get unexpected results if you mix up the order of
the arguments in a function call when using positional arguments
2. Passing Arguments
B. Keyword Arguments
• A keyword argument is a name-value pair that you pass to a function.
• You directly associate the name and the value within the argument.
• Keyword arguments free you from having to worry about correctly ordering your arguments in the
function call, and they clarify the role of each value in the function call.

def describe_pet(animal_type, pet_name):


"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='hamster', pet_name='harry')

• The function describe_pet() hasn’t changed. But when we call the function, we explicitly tell Python
which parameter each argument should be matched with.
• The order of keyword arguments doesn’t matter because Python knows where each value should
go.
2. Passing Arguments
C. Default Values
• When writing a function, you can define a default value for each parameter.

• If an argument for a parameter is provided in the function call, Python uses the argument value. If
not, it uses the parameter’s default value.

• So when you define a default value for a parameter, you can exclude the corresponding
argument you’d usually write in the function call.

• Using default values can simplify your function calls and clarify the ways your functions are used.

def describe_pet(pet_name, animal_type='dog'):

"""Display information about a pet."""

print(f"\nI have a {animal_type}.")

print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet(pet_name=‘willie')

describe_pet(pet_name='harry', animal_type='hamster')
2. Passing Arguments
D. Equivalent Function Calls
# A dog named Willie.
describe_pet('willie')
describe_pet(pet_name='willie')
# A hamster named Harry.
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name=‘harry')
E. Avoiding Argument Errors

def describe_pet(animal_type, pet_name):


"""Display information about a pet.”""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet()
3. Return Values
A.Returning a Simple Value
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician) ——> # expected output Jimi Hendrix

B. Returning a Dictionary

def build_person(first_name, last_name):


"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
3. Return Values
c. Using a Function with a while Loop
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print(f"\nHello, {formatted_name}!")
4. Passing a List
A. Using a Function with a while Loop
4. Passing a List
B. Modifying a List in a Function
• When you pass a list to a function, the function can modify the list.
• Any changes made to the list inside the function’s body are permanent, allowing you to work
efficiently even when you’re dealing with large amounts of data.
• Consider a company that creates 3D printed models of designs that users submit.
• Designs that need to be printed are stored in a list, and after being printed they’re moved to a
separate list.
4. Passing a List
B. Modifying a List in a Function
4. Passing a List
C. Preventing a Function from Modifying a List
• Sometimes you’ll want to prevent a function from modifying a list.
• In this case, you can address this issue by passing the function a copy of the list, not the original.
• Any changes the function makes to the list will affect only the copy, leaving the original list intact.
remove_odds(number_list[:])
5. Passing an Arbitrary Number of Arguments
• Sometimes you won’t know ahead of time how many arguments a function needs to accept.
• Fortunately, Python allows a function to collect an arbitrary number of arguments from the
calling statement.
5. Passing an Arbitrary Number of Arguments
A. Mixing Positional and Arbitrary Arguments
• If you want a function to accept several different kinds of arguments, the parameter that
accepts an arbitrary number of arguments must be placed last in the function definition.
• Python matches positional and keyword arguments first and then collects any remaining arguments
in the final parameter.
• For example, if the function needs to take in a size for the pizza, that parameter must come before
the parameter *toppings

def make_pizza(size, *toppings):


"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}”)

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
5. Passing an Arbitrary Number of Arguments
B. Using Arbitrary Keyword Arguments
• Sometimes you’ll want to accept an arbitrary number of arguments, but you won’t know ahead of
time what kind of information will be passed to the function.
• In this case, you can write functions that accept as many key-value pairs as the calling statement
provides.
• One example involves building user profiles: you know you’ll get information about a user, but
you’re not sure what kind of information you’ll receive.
• The function build_profile() in the following example always takes in a first and last name, but it
accepts an arbitrary number of keyword arguments as well:
6. Storing Your Functions in Modules
• One advantage of functions is the way they separate blocks of code from your main program.
• When you use descriptive names for your functions, your programs become much easier to follow.
• You can go a step further by storing your functions in a separate file called a module and then
importing that module into your main program.
• An import statement tells Python to make the code in a module available in the currently running
program file.
• It also allows you to reuse functions in many different programs.
• When you store your functions in separate files, you can share those files with other programmers
without having to share your entire program.
• Knowing how to import functions also allows you to use libraries of functions that other
programmers have written.
6. Storing Your Functions in Modules
A. Importing an Entire Module
• To start importing functions, we first need to create a module. A module is a file ending in .py that
contains the code you want to import into your program.
• Let’s make a module that contains the function make_pizza(). To make this module, we’ll remove
everything from the file pizza.py except the function make_pizza():
• First file: pizza.py —-> This our module we need to import
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}”)
6. Storing Your Functions in Modules
B. Importing Specific Functions
• from module_name import function_name
• from module_name import function_0, function_1, function_2
C. Using as to Give a Function an Alias
• from module_name import function_name as fn
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese’)
D. Using as to Give a Module an Alias
• import module_name as mn
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese’)
E. Importing All Functions in a Module
• from module_name import *
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

You might also like