Lecture4 1
Lecture4 1
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.
• 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.
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
B. Returning a Dictionary
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')