0% found this document useful (0 votes)
16 views33 pages

Session10 Dictionaries

Uploaded by

pawan kamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views33 pages

Session10 Dictionaries

Uploaded by

pawan kamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Dictiona

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:

{'name': 'Karan', 'age': 19, 'eligible': True}


{'name': 'Karan', 'age': 20, 'eligible': True, 'DOB': 2001}
setdefault()
The setdefault() method in Python dictionaries is used to retrieve the value of a specified
key. If the key does not exist in the dictionary, it will insert the key with a specified default
value. This method is helpful when you want to ensure that a key exists in the dictionary
and has a value, without having to check manually

# Creating a dictionary
my_dict = {'name': 'Alice', 'age': 25}

# Using setdefault() to get the value of an existing key


value = my_dict.setdefault('name', 'Unknown')
print(value) # Output: Alice

# Using setdefault() to add a new key with a default value


new_value = my_dict.setdefault('city', 'New York')
print(new_value) # Output: New York

# The updated dictionary


print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
pop()
The pop() method removes the key-value pair whose key is
passed as a parameter.

Example:

info = {'name':'Karan', 'age':19, 'eligible':True}


info.pop('eligible')
print(info)

Output:

{'name': 'Karan', 'age': 19}


popitem()
The popitem() method removes the last key-value pair from
the dictionary.

Example:

info = {'name':'Karan', 'age':19, 'eligible':True,


'DOB':2003}
info.popitem()
print(info)

Output:

{'name': 'Karan', 'age': 19, 'eligible': True}


clear()
The clear() method removes all the items from the list.

Example:

info = {'name':'Karan', 'age':19, 'eligible':True}


info.clear()
print(info)

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:

NameError: name 'info' is not defined


Leftovers
 #Misc. Dictionary operations
 d={'Jhon': 34, 1: 23, ‘raj': 25, 22: 'abc', 'Alice': None,
'Joe': 48}
 s={'Jhon':32,'ken':19}
 d.update(s)
 print(d)#Existing key gets updated and new key gets added
 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)

{'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}

l=sorted(d)#returns sorted list of key


print(l)
Output- ['Alice', 'Harry', 'James', 'Jhon', 'Joe', 'Ram’]

l=sorted(d.keys())#returns list of key


print(l)
Output- ['Alice', 'Harry', 'James', 'Jhon', 'Joe', 'Ram’]

l=sorted(d.items())#returns list of sorted key value pair


based on key
print(l)
Output- [('Alice', 56), ('Harry', 25), ('James', 97),
Sorting
l=sorted(d.values())#returns list of values
print(l)
Output-[23, 25, 34, 48, 56, 97]

l=sorted(d.items(), key=lambda x:x[1])#sort dictionary on


value
print(l)
Output- [('Ram', 23), ('Harry', 25), ('Jhon', 34), ('Joe',
48), ('Alice', 56), ('James', 97)]

l=sorted(d.items(), key=lambda x:x[0])#sort dictionary on


keys
print(l)

Output-[('Alice', 56), ('Harry', 25), ('James', 97),


('Jhon', 34), ('Joe', 48), ('Ram', 23)]
Nested values(left)
#nested values & updation d={1:
['ab',34,45.67],23:['rt','yt','lo']}
d[1][1]=90
print(d)

Output- {1: ['ab', 90, 45.67], 23:


['rt', 'yt', 'lo’]}
d={'ab':{'a':2,'b':34},'bc':
{'x':89,90:'n'}} d['ab']['a']=4
print(d)

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))

Output- {'ram': None,


23.67: None, ('shyam',
67): None}

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

Loop completed without interruption


lambda function
A lambda function in Python is a small, anonymous function defined using the lambda
keyword.
It can have any number of arguments but only one expression.
It's often used when you need a simple function for a short period of time.

Syntax-
lambda arguments: expression

Ex-
# Lambda function to add two numbers
add = lambda x, y: x + y

# Using the lambda function


result = add(5, 3)
print(result) # Output: 8
lamda
# Function to double the input
def double(x):
return x * 2

# Lambda function to double the input


lambda x: x * 2
```
The above lambda function has the same functionality as the
double function defined earlier. However, the lambda
function is anonymous, as it does not have a name.
Lambda lamda
"""Lambda is a tiny function just like macro
in C"""
import math
square=lambda n:n*n
print(square(4)) #16
"""without arguement"""
x=lambda : math.factorial(4)
y=x()
print(y) #24
x=lambda x: math.factorial(x)
y=x(3)
print(y) #6
z=lambda:sum(range(1,4))
y=z()
print(y) #6
p=lambda x:print(x)
p("hello world") #hello world
w=square(3)
print(w) #9s

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

Functions and methods are first-class citizen (objects) in Python, so if we want


to pass a function as an argument to another function, we can just treat it as
any other object.
It’s worth noting that in some languages functions and objects are distinct, but
in python functions are implemented as objects (That also means functions have
Higher order function
sorted does pretty much the same thing what you expected.
# sorting numbers
In [0]: sorted([9, 5, 7])
Out[0]: [5, 7, 9]
# sorting alphabetically
In [0]: sorted(['foo', 'bar'])
Out[0]: ['bar', 'foo’]
Using Key :key:
Well you can also customize the sorting also, the parameter key. The key needs
to be a simple function the takes a single value that tells python the value to use
in sorting it.
In [0]: sorted([1, -3, 2]) # sorting normally
Out[0]: [-3, 1, 2]
In [0]: sorted([1, -2, 0], key=abs) # sorting by absolute values
Out[0]: [0, 1, -2]
Note: abs is the absolute value function. i.e. abs(-3) = 3
Higher order function

In Python, the map, filter,


and reduce functions are
built-in functions that
allow you to apply a
function to a sequence of
elements and return a new
sequence. These functions
are known as higher-order
functions, as they take
other functions as
arguments.
map
Takes an input iterable of values and return a list with different values. Same order, same
length, but mapped via a function.
map(function, iterable) map takes a function as the first parameter and then an iterable
containing data.
Ex-
def twice(x):
return 2*x
ans= map(twice, [1, 2, 3, 4, 5])
print(ans)

Output -<map object at 0x7acb29ac2e30>

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])

for item in ans:


print(item, end=“”)

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)

 The predicate argument is a function that returns a boolean value


and is applied to each element in the iterable argument. The
iterable argument can be a list, tuple, or any other iterable
object.

In [0]: def greater_than_5(x):


return x > 5
In [1]: filter(greater_than_5, range[10])
Out[1]: [6, 7, 8, 9]
filter
Special case: When None is passed instead of function, it will filter by Truthiness.
filter(None, [0, 2, 1, 3])
[2, 1, 3]
filter(None, ['a','', 'b' ])
['a', ‘b’]

# filter using with lambda-


# List of numbers
numbers = [1, 2, 3, 4, 5]

# Get only the even numbers using the filter function


evens = filter(lambda x: x % 2 == 0, numbers)

# Print the even numbers


print(list(evens)) #[2,4]
reduce
• reduce takes an iterable of input data and consumes it to come up
with a single value.

• The reduce function is a higher-order function that


applies a function to a sequence and returns a single
value. It is a part of the functools module in Python.

• The reduce function applies the function to the first two


elements in the iterable and then applies the function to
the result and the next element, and so on. The reduce
function returns the final result.
Ex-
from functools import reduce

numbers = [1, 2, 3, 4, 5]

# Calculate the sum of the numbers using the reduce function


sum = reduce(lambda x, y: x + y, numbers)
print(sum) #15
reduce
The function we have to write is different too - the function will take
two values and typically reduce will consume the first two values from
the iterable then consume one value at a time from the list using the
return value from the previous call.

In [3]: def add(x,y):


...: return x + y
...:

In [4]: reduce(add, [1,2,3,4])


Out[4]: 10

You might also like