Python
Dictionary
Methods
• Clear()
• Copy()
• Get()
• Items()
• Keys()
python
• Popitem() ,.
Diet • Values()
• Pop()
• Update()
• Setdefault()
clear()
The clear() method removes all items from
the dictionary.
my _di.ct = { 'name' : 'Aasi.f' , 'age ' : 25 }
my _di.ct. clear ()
pri.nt (my_di.ct)
copy()
The copy() method returns a shallow copy
of the dictionary.
changes to the copy of the dictionary do not affect the
original dictionary.
my_dict = { 'name ' : 'Aasif' , 'age' : 25 }
new_dict = my_dict . copy ()
new_dict[ 'age' ] = 30
print (my_dict)
pr1nt (new_d1ct)
get()
The get() method returns the value of the
specified key. If the key is not present in the
dictionary, it will return None
my_di.ct = { 'name' : ' Aasi.f' , ' age ': 25 }
age = my_di.ct. get ( 'age ')
pri.nt (age)
occupati.on = my _di.ct .get ( 'occupati.on' )
pri.nt (occupati.on)
occupation= my_di.ct .get
( 'occupat i.on' , 'unemployed' )
pri.nt (occupati.on)
items()
The items() method returns a list of
key-value pairs in the dictionary.
my _di.ct = { • name• : Aas i. f
1 1
, • age 1
: 25 }
i.tems = my_di.ct . i.tems ()
pri.nt (i.tems)
keys()
The keys() method returns a list of keys in
the dictionary.
my_dict = { 'name' : 'Aasif' , 'age' : 22 }
keys = my _dict. keys ()
pri.nt (keys)
values()
The values() method Returns a list of
values in the dictionary.
my_dict = { 'name' : 'Aasif' , 'age' : 22 }
values = my_dict . values ()
print (values)
pop{)
The pop() method removes and returns the value
of the specified key. If the key does not exist, it
raises a KeyError. To avoid this, you can pass a
default value to be returned if the key is not found.
my _di.ct = { 'name' : 'Aasi.f' , 'age ' : 25 }
age= my_di.ct. pop ( 'age' )
pri.nt (age)
pri.nt (my_di.ct)
update()
The update() method updates the dictionary
with the specified key-value pairs .
my _di..ct = { 'name' : 'Aas if ', 'age' :
22 , 'country' : 'i.ndi.a' }
my_di..ct. update ({ 'age' : 23 })
pri..nt(my _di..ct)
.................................................................. ,
setdefault()
The setdefault{) method returns the value
of the specified key
my_di..ct={ 'name' : ' Aasi..f' , 'a ge' : 22 }
country= my_di..ct .
setdefaul t ( ' country ', 'i..ndi..a' )
pri..nt (country)
pri..nt( my_di..ct)
@Join Me on a Journey of Full Stack Development! ~
Utsav Desai
Full Stack Developer
@utsavdesal26
If You Really Found This Post Useful,
Then Please Follow For More