List and Dictionaries
Objectives
In this session, you will learn to use:
List.
Understanding List Operations and Methods.
Parsing Lines.
Implementing Objects, Values and Arguments.
Use Dictionaries Functions and Methods.
Differences between Lists and Dictionaries.
List
Most versatile datatype available in python.
Defined as a sequence of values.
Holds Homogenous set of items.
Indices start at 0.
Lists are Mutable.
Example:
>>>list1=[17,119]
>>>list1=[10,20,30,40] >>>list[1]=90
>>>list2=['Harish','Suresh','Kunal','Girish’] >>>print list1
[17,90]
Traversing List
Traversing means visiting all the elements in the list.
Traversing is required to Search, Update and Delete values
from List. >>>numbers=[10,20,30,40]
dept=['IT','CSE','ECE','CSE']>>>for i in range(len(numbers)):
for d in dept: numbers[i]=numbers[i]*2
print(d) print(numbers[i])
IT
CSE
ECE Output 20
CSE 40
60
80
List Operations &
Slices
Examples
Operators used in list >>>a=[1,2,3]
>>>b=[4,5,6]
+ - used to concatenate the list. >>>c=a+b
>>>print(c)
Output : [1,2,3,4,5,6]
* - used to repeat a list for a number of times.
>>>a=[10,20,30]
>>>a*2
: - used to check a range of characters. Output:
[10,20,30,10,20,30]
>>>
alpha=['a','b','c','d','e',
'f']
>>> alpha[1:3]
Output :['b', 'c‘]
List Methods
The following methods are used in Python for manipulating the
list:
Method Name Description
append() This method is used to add a new element to the end of a list.
extend() This method is used to take a list as an argument and appends all the
elements.
sort() This method is used to arrange the elements of the list from low to
high.
Example
mylist=['A','B','C
']
mylist.append('D')
print(mylist)
List Methods
(Contd.)
There are several ways to delete elements from a list.
Ways Description
pop() method It modifies the list and returns the element that was removed. If we
don't provide an index value then it deletes the last element and
returns the value.
del operator If we do not want to retain the value which we have deleted using an
index then we need to use the del operator.
remove() method If we know the element to be removed then we can use the remove()
method.
Example
>>> mylist1=['A','B','C']
>>> element=mylist1.pop(1)
>>> print(mylist1)
['A', 'C']
List Functions
There are a number of built in functions that can be used on lists.
Function Name Description
sum() Using this function we can add the elements of the list. It will work only with
the numbers.
min() Using this function we can find the minimum value from the list.
max() Using this function we can find the maximum value from the list
len() Using this function we can find the number of elements in the list.
Example
numbers = [10,20,30,40,50]
print(len(numbers))
String and Its
Methods
String Is a sequence of characters.
Methods in Strings
list() is used to convert a string to list of characters.
split() is used to break the string into list of words.
split() takes an optional argument called delimiter which specifies the
word boundaries.
str = 'I am studying in NIIT'
t = str.split()
print(t)
Parsing of Lines
Parsing means, dividing a string into tokens based on some
delimiters.
It is used to find a particular word from a file or search a
pattern
Example Code: Contents of MyText.txt
From
[email protected]fhand = open('Mytxt.txt') Sat Jan 5 09:14:16 2008
for line in fhand:
line = line.rstrip() Output:
if not line.startswith('From ') : Sat
continue
words = line.split()
print(words[2])
Activity
Activity : Understanding Collection
Problem Statement:
Operations
Write a menu based program to insert , remove, sort, extend, reverse and traverse a list of
items.
Hint: Define functions to perform different operation of list, such as insertList() and
removeList() etc.
Objects & Values
In python every data is represented as an Object.
Example:
In the preceding example, obj1 and obj2 are pointing to the
same string hence they are identical.
Objects & Values
(Contd.)
Example:
In the preceding example obj1 and obj2 are pointing to the
same values hence they are equivalent . But they are not
identical.
Aliasing
The association of a variable with an object is called a reference.
An object with more than one reference, has more than one name and is
called as aliasing.
List Arguments
List can be passed as an argument to a function.
Passing a list as an argument to a function gets the reference
of the list.
Just a Minute
_____ method is used to break the
string into list of words.
Just a Minute
_____ method is used to break
the string into list of words.
Answer: split
Introduction to Dictionary
Dictionary
It is a “bag” of values, each with its own label.
It contains the values in the form of key-value pair.
Every value in Dictionary is associated with a key.
tissue
candy
perfume
calculator
money
Characteristics of
Dictionary
Dictionaries are Python’s most powerful data collection.
Dictionaries allow us to do fast database-like operations in
Python.
Dictionaries have different names in different languages.
Associative Arrays - Perl / PHP.
Properties or Map or HashMap – Java.
Property Bag - C# / . NET.
Dictionary Keys can be of any Python data type.
Because keys are used for indexing, they should be immutable.
Dictionary Values can be of any Python data type.
Values can be mutable or immutable.
Creating a
Dictionary
Dictionary literals use curly braces and have a list of key-value pairs.
You can make an empty dictionary using empty curly braces
Example of a Dictionary
Creating a Dictionary
(Contd.)
Lists index their entries based on the position in the list.
In general, the order of items in a dictionary is unpredictable.
Dictionaries are indexed by keys.
Example:
Methods of Dictionary
S.No Method Name Description
1
dict.clear() Removes all elements of the dictionary ”dict”
2 Returns a shallow copy of dictionary ”dict”
dict.copy()
3 Returns a new dictionary with keys from a supplied seq and
dict.fromkeys(seq[, value]) values all set to specified value
4 Returns value of given key or returns default if key not in
dict.get(key, default=None) dictionary.
5
Returns true if key in dictionary ”dict” false otherwise
dict.has_key(key)
6 Returns a list of (key, value) tuple pairs from dictionary “dict”
dict.items()
7 Returns list of keys from dictionary “dict”
dict.keys()
8 Similar to get(), but will set dict[key]=default if key is not
dict.setdefault(key, default=None) already in “dict”
9 Adds dictionary ”dict2” key-values pairs to ”dict”
dict.update(dict2)
10 Returns list of values from dictionary ”dict”.
dict.values()
Keys and Values
The keys() method returns a list of the keys in a dictionary.
The values() method returns a list of the values.
5/10/09 Python Mini-Course: Lesson 16 23
Keys and Values (Contd.)
The items() method returns a list of tuple pairs of the key-value
pairs in a dictionary.
5/10/09 Python Mini-Course: Lesson 16 24
Keys and Values (Contd.)
To access dictionary elements, you can use the familiar square
brackets along with the key to obtain its value.
Example:
5/10/09 Python Mini-Course: Lesson 16 25
Len() Function
The len() function works on dictionaries.
Len() returns the number of key-value pair.
Example:
5/10/09 Python Mini-Course: Lesson 16 26
“in” Operator
The “in” Operator works differently for dictionaries than for
other sequences as below
It tells whether data appears as a key in the dictionary.
It can be used to check whether a value exists in a dictionary.
values() method
It checks the values existing in a dictionary.
It will return the result as a List.
5/10/09 Python Mini-Course: Lesson 16 27
“in” Operator
(Contd.)
Example:
5/10/09 Python Mini-Course: Lesson 16 28
“get()” Method for
Dictionary
The method get() returns a value for the given key.
If key is not available, it returns default value “None”.
key- This is the key to be searched in the dictionary.
default - This is the value to be returned in case key does not exist.
Example:
Traversing a
Dictionary
We can write a “for” loop that goes through all the entries in a dictionary,
such as keys and values.
If a dictionary uses in a “for” statement, it traverses the keys of the dictionary.
This loop prints each key and the corresponding value.
Example:
Dictionary Traceback
It is an error to reference a key which is not in the dictionary.
We can use the “in” operator to see if a key is in the dictionary.
List vs Dictionary
LIST DICTIONARY
It is an index of words and each of them has a
List is list of values. Starting from zero. definition.
Element can be added in Dictionary in the form
We can add the element index wise. of key-value pair.
Just a Minute
Predict the output of the
following Code:
Data={‘Apple’,’Orange’,’Grapes’}
‘Apple’ in Data
Just a Minute
Predict the output of the
following Code:
Data={‘Apple’,’Orange’,’Grapes’}
‘Apple’ in Data
Answer: True
Activity
Activity : Implementing Dictionary
Problem Statement:
Collection
Write a program to create two dictionary objects named states and cities with the following
items:
States : Cities :
'Oregon': 'OR' 'CA': 'San Francisco'
'Florida': 'FL' 'MI': 'Detroit'
'California': 'CA' 'FL': 'Jacksonville'
'New York': 'NY'
'Michigan': 'MI'
In addition add more two items to the cities dictionary(NY-New York, OR-Portland). Then
print the details available in cities dictionary using keys and values.
Summary
In this session we have learned:
Parsing means dividing a string into tokens based on some delimiters.
An object comprises both data members (class variables and instance
variables) and methods.
An object with more than one reference has more than one name and
hence the object is said to be aliased.
Creating a dictionary.
Different methods in a dictionary.
“in” operator for checking the keys existing in dictionary.
Traversing through the Dictionary.
Differences between List and Dictionary.