Session10 Dictionaries
Session10 Dictionaries
ry
The dictionary data structure
In Python, a dictionary is mapping between a set of indices (keys)
and a set of values
The items in a dictionary are key-value pairs
Keys can be any Python data type
Because keys are used for indexing, they should be immutable
Values can be any Python data type
Values can be mutable or immutable
#In general, the order of items in a dictionary is unpredictable
#Dictionaries are indexed by keys, not integers
#Note that the in operator works differently for dictionaries
than for
other sequences
• For offset indexed sequences (strings, lists, tuples), x in y
checks to see whether x is an item in the sequence
• For dictionaries, x in y checks to see whether x is a key
in the dictionary
Creating a Dictionary
#Creating Dictionary
d=dict()#Empty Dictionary
print(type(d))#<class
'dict'> d={}
print(type(d))#<class
'dict'>
#Initialization-ex a key
Value pair of Name & Age
d={"Ram":30, "Jai":40}
print(d)
Output-
{'Ram': 30, 'Jai': 40}
Accessing Values
#Accessing Dictionary Values
d={'Ram': 30, 'Jai': 40, 'Hari': 25, 'Shyam': 30,
'Jhon': 25}
x=d['Ram']
print(x)# 30
print(d['Ram'])# 30
print(d.get('Ram'))# 30
print(d.setdefault("Ram"))# 30
#KeyError--if key is not present python raises
exception
print(d['James'])# KeyError: 'James'
print(d.setdefault(“Anu"))#None
Adding Elements
#Adding values to dictionary
d={}
d['James']=7
8 print(d)
d.update({‘R
am':42})#if
key present
updates
value else
add key to
dictionary
print(d)
d.setdefault('Syam',2
6) print(d)
#using user input
d[input('Enter
Key')]=eval(input('En
ter Value'))
print(d)
d.setdefault(input('E
nter
Suppressing keyError
#Supressing KeyError
d={"Jhon":34, 1:23, "Harry":25, 22:'abc'}
#Accessing a key not present--suppressing keyError--
Method--1
print(d.get("Alice"))#returns None by
default print(d)#Alice will not be added
as a key in d ##Customizing get
#Override default None by Some customized
value print(d.get("Alice", "Key not found
in dict")) #Method--2
print(d.setdefault("Alice"))
#returns None and key added to
dictionary--value None
print(d.setdefault("Joe", 48))
#returns 48 and key added--value 48
print(d)
Keys, values, items
#keys,values and items
d={'Jhon': 34, 1: 23, 'Harry': 25, 22: 'abc', 'Alice': 32,
'Joe': 48}
l=d.keys()#returns object dict_keys
#dict_keys(['Jhon', 1, 'Harry', 22, 'Alice', 'Joe'])
print(l)
t=d.values()#returns dict_values
#dict_values([34, 23, 25, 'abc', 32,
48]) print(t)
s=d.items()#returns dict_items-- (key,value)
#dict_items([('Jhon', 34), (1, 23), ('Harry', 25), (22,
'abc'),
('Alice', 32), ('Joe', 48)])
print(s)
print(type(l))#<class
'dict_keys'>
print(type(t))#<class
'dict_values'>
Iterating Dictionary
#iterating dictionary
d={'Jhon': 34, 1: 23, 'Harry': 25, 22: 'abc', 'Alice':
None,
'Joe': 48}
Output-
for i in
d.keys(): Jhon 34
1 23
print(i,d[i] Harry 25
22 abc
) Alice None
Joe 48
for k,v in
d.items(): Jhon 34
1 23
print(k,v) Harry 25
22 abc
Alice None
Joe 48
Dictionary Methods-
update()-
The update() method updates the value of the key provided
to it if the item already exists in the dictionary, else it
creates a new key-value pair.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
info.update({'age':20})
info.update({'DOB':2001})
print(info)
Output:
# Creating a dictionary
my_dict = {'name': 'Alice', 'age': 25}
Example:
Output:
Example:
Output:
Example:
Output:
{}
del
we can also use the del keyword to remove a dictionary item.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True,
'DOB':2003}
del info['age']
print(info)
Output:
{'name': 'Karan', 'eligible': True, 'DOB': 2003}
If key is not provided, then the del keyword will delete the
dictionary entirely.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True,
'DOB':2003}
del info
print(info)
Output:
{'Jhon': 32, 1: 23, ‘raj': 25, 22: 'abc', 'Alice': None, 'Joe': 48, 'ken': 19}
{'ram': None, 23.67: None, ('shyam', 67): None}
{'ram': -1, 23.67: -1, ('shyam', 67): -1}
15
Sorting
#sorting dictionary
d={'Jhon': 34, 'Ram': 23, 'Harry': 25, 'James': 97, 'Alice':
56,
'Joe': 48}
Output-
{'ab': {'a': 4, 'b': 34},
'bc': {'x': 89, 90: 'n'}}
18
Nested values(left)
l=['ram',23.67,
('shyam',67)] dt={}
dt=dt.fromkeys(l)
#creates dictioanry from
a sequence of immutable-
value is None
print((dt))
dt=dt.fromkeys(l,-
1)#default value is -1
print(dt)
else in loop
The else block in a for loop (or a while loop) in Python is unique.
It runs after the loop finishes executing all its iterations, but only if the loop was not
terminated by a break statement.
If the loop is terminated using break, the else block is skipped.
Ex-1
for x in range(5):
if x == 3:
break
print("Iteration no {} in for loop".format(x + 1))
else:
print("Else block in loop") # This won't be executed because of the break
print("Out of loop")
Output-
Iteration no 1 in for loop
Iteration no 2 in for loop
Iteration no 3 in for loop
Out of loop
Ex- 2
i=0
While i<5:
print(i)
i+=1
else:
print("Loop completed without interruption")
Output-
0
1
2
3
4
Syntax-
lambda arguments: expression
Ex-
# Lambda function to add two numbers
add = lambda x, y: x + y
24
Higher order function
“Functions that take a function as an argument or return a
function.
Called higher order function”
Example:
def foo(f):
f() # calling the function that is passed
def bar():
print "Hello bar"
foo(bar) # function bar is passed to function foo.
Output - Hello bar
The conversion to a list (list(ans)) is required to immediately evaluate and display all the
values from the map object.
print(list(ans)) #ouput-[2,4,6,8,10]
map
The reason you need to type cast map() to list in order to get the output is that the
map() function in Python 3 returns a map object, which is an iterator. Iterators do not
compute their values immediately; instead, they produce the values one by one when
you iterate over them. To see the output all at once, you need to convert it to a list or
iterate through it.
Alternative Ways:
You can also use a for loop to iterate through the map object without converting it to a
list:
def twice(x):
return 2*x
ans= map(twice, [1, 2, 3, 4, 5])
Output – 2 4 6 8 10
filter
filter takes a function and an iterable and produces an output list of every
item on the input list that passes a test.
The filter function filters a sequence of elements based on a
given predicate (a function that returns a boolean value) and
returns a new sequence containing only the elements that meet the
predicate. The filter function has the following syntax:
filter(predicate, iterable)
numbers = [1, 2, 3, 4, 5]