Lab_03
Lab_03
Objectives:
➢ To learn and to use create, modify dictionary and access their elements
➢ To learn and able to use built-in functions of dictionary
➢ To learn and able to use the dictionary with loop
➢ To learn and able to use strings and different string function
Outcomes:
➢ Students should be able to create, modify dictionary and access their elements
➢ Students should be able to use built-in functions of dictionary in different programs.
➢ Students should be able to iterate the dictionary and able to use dictionary with loop
➢ Students should be able to work with strings and string functions
3.1 Dictionary
Dictionaries are Python’s implementation of a data structure that is more generally known as an associative
array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its
associated value.
You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A
colon (:) separates each key from its associated value:
The following defines a dictionary that maps a location to the name of its corresponding Major League
Baseball team:
You can also construct a dictionary with the built-in dict() function. The argument to dict() should be a
sequence of key-value pairs. A list of tuples works well for this:
Once you’ve defined a dictionary, you can display its contents, the same as you can do for a list. All three
of the definitions shown above appear as follows when displayed:
The entries in the dictionary display in the order they were defined. But that is irrelevant when it comes to
retrieving them. Dictionary elements are not accessed by numerical index:
A value is retrieved from a dictionary by specifying its corresponding key in square brackets ([]):
If you refer to a key that is not in the dictionary, Python raises an exception:
Adding an entry to an existing dictionary is simply a matter of assigning a new key and value:
If you want to update an entry, you can just assign a new value to an existing key:
To delete an entry, use the del statement, specifying the key to delete:
You may have noticed that the interpreter raises the same exception, Key Error, when a dictionary is
accessed with either an undefined key or by a numeric index:
In fact, it’s the same error. In the latter case, [1] looks like a numerical index, but it isn’t.
You will see later in this tutorial that an object of any immutable type can be used as a dictionary key.
Accordingly, there is no reason you can’t use integers:
In the expressions MLB_team[1], d[0], and d[2], the numbers in square brackets appear as though they
might be indices. But they have nothing to do with the order of the items in the dictionary. Python is
interpreting them as dictionary keys. If you define this same dictionary in reverse order, you still get the
same values using the same keys:
The syntax may look similar, but you can’t treat a dictionary like a list:
3.4 Building a Dictionary Incrementally
Defining a dictionary using curly braces and a list of key-value pairs, as shown above is fine if you know
all the keys and values in advance. But what if you want to build a dictionary on the fly?
You can start by creating an empty dictionary, which is specified by empty curly braces. Then you can add
new keys and values one at a time:
Once the dictionary is created in this way, its values are accessed the same way as any other dictionary:
Retrieving the values in the sub list or sub dictionary requires an additional index or key:
Just as the values in a dictionary don’t need to be of the same type, the keys don’t either:
Here, one of the keys is an integer, one is a float, and one is a Boolean. It’s not obvious how this would be
useful, but you never know.
Notice how versatile Python dictionaries are. In MLB_team, the same piece of information (the baseball
team name) is kept for each of several different geographical locations. person, on the other hand, stores
varying types of data for a single person.
You can use dictionaries for a wide range of purposes because there are so few limitations on the keys and
values that are allowed. But there are some. Read on!
Almost any type of value can be used as a dictionary key in Python. You just saw this example, where
integer, float, and Boolean objects are used as keys:
You can even use built-in objects like types and functions:
However, there are a couple restrictions that dictionary keys must abide by.
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps
each key to a corresponding value, so it doesn’t make sense to map a particular key more than once.
You saw above that when you assign a value to an already existing dictionary key, it does not add the key
a second time, but replaces the existing value:
Similarly, if you specify a key a second time during the initial creation of a dictionary, the second
occurrence will override the first:
Secondly, a dictionary key must be of a type that is immutable. You have already seen examples where
several of the immutable types you are familiar with—integer, float, string, and Boolean—have served as
dictionary keys.
However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries
are mutable:
You have already become familiar with many of the operators and built-in functions that can be used with
strings, lists, and tuples. Some of these work with dictionaries as well.
For example, the in and not in operators return True or False according to whether the specified operand
occurs as a key in the dictionary:
In the second case, due to short-circuit evaluation, the expression MLB_team['Toronto'] is not evaluated,
so the KeyError exception does not occur.
As with strings and lists, there are several built-in methods that can be invoked on dictionaries. In fact, in
some cases, the list and dictionary methods share the same name. (In the discussion on object-oriented
programming, you will see that it is perfectly acceptable for different types to have methods with the same
name.
MLB_teams.get(<key>) searches dictionary d for <key> and returns the associated value if it is found. If
<key> is not found, it returns None:
If <key> is not found and the optional <default> argument is specified, that value is returned instead of
None:
MLB_teams.items() returns a list of tuples containing the key-value pairs in mlb_teams. The first item in
each tuple is the key, and the second item is the key’s value:
• MLB_teams.keys() Returns a list of keys in a dictionary.
MLB_teams.keys() returns a list of all keys in MLB_teams:
If <key> is not in d, and the optional <default> argument is specified, then that value is returned, and no
exception is raised:
• d.update(<obj>) Merges a dictionary with another dictionary or with an iterable of key-value pairs.
If <obj> is a dictionary, d.update(<obj>) merges the entries from <obj> into d. For each key in <obj>:
If the key is not present in d, the key-value pair from <obj> is added to d.
If the key is already present in d, the corresponding value in d for that key is updated to the value from
<obj>.
In this example, key 'b' already exists in d1, so its value is updated to 200, the value for that key from d2.
However, there is no key 'd' in d1, so that key-value pair is added from d2.
<obj> may also be a sequence of key-value pairs, similar to when the dict() function is used to define a
dictionary. For example, <obj> can be specified as a list of tuples:
Or the values to merge can be specified as a list of keyword arguments:
Task 1: Write python program to display name entered by user followed by good afternoon using input
function.
Code:
name=input("name ")
Output:
Task 2: Write a program to fill in letter template given bellow with name and date
Letter=”Dear </name/>, you are selected </date/>
Code:
name=input("enter name")
date=input("date")
letter=letter.replace("student",name)
letter=letter.replace("date",date)
print(letter)
Output:
Code:
str=str.find(" ")
print(str)
Output:
Code:
print(str)
Output:
Task 4: Write a program to format following letter by using escape sequence character
St=”Dear member This python course is nice thanks!.”
Code:
print(str)
Output:
Lab Tasks