Data Structure (Dictionary)
Data Structure (Dictionary)
d = { }
d = dict()
How to access a dict element.
❖ The dict's elements can be accessed by using a key value.
❖ Syntax to access the dict element.
variable_name.get(key_value)
❖ Example:
1 biodata = {‘name’:’Karma’,’school’:’PHSS’}
2 #Code to access the above dict element
3 x=biodata.get(‘name’) #Karma
4 print(x)
print(biodata.get(‘school’))#PMSS
print(biodata.values())
Print(biodata.keys())
How to delete a dict element.
❖ The dict's elements can be deleted by referring to a key value.
❖ del keyword is used to delete an element in the dict.
❖ Syntax to delete a dict element
❖ Example:
1 biodata = {‘name’:’Karma’,’school’:’PHSS’}
2 #Code to delete a dict element
3 del biodata[‘name’]#deleting karma from the dict
4 print(biodata) #{‘school’:’PHSS’} new dict
biodata.pop(‘school’)
How to update a dict element.
❖ The dict's elements can be updated by referring to a key value.
❖ Syntax to update a dict element.
variable_name[key_Value] = value
❖ Example:
1 . biodata = {‘name’:’Karma’,’school’:’PHSS’}
2 #Code to update a dict element
3 biodata[‘name’]= “Tshering”#updating Tshering to the dict.
4 print(biodata) #{‘name’:’Tshering’,‘school’:’PHSS’}#updated
dict
How to add a dict element.
❖ A new dict element can be added by inserting a new key value.
❖ Syntax to add a new element.
❖ Example:
1 biodata = {‘name’:’Karma’,’school’:’PHSS’}
2 #Code to add a new dict element
3 biodata[‘DOB’]= “12/2/2023”#adding DOB to the dict.
4 biodat.update({‘section’:’A’})
print(biodata)
#{‘name’:’Karma’,‘school’:’PHSS’,’DOB’:’12/2/2023’}#updated
dict
Dict Methods:
SL_No Method Description Example
d={“name”:”Nima”,”Age”:15}
2) Write a python code that returns a list containing the dictionary's keys.
3) Write a python code that removes the element with the specified key.
4) Write a python code that updates the dictionary with the specified key-value pairs.
Answer 1
1) Write a python code that returns the value of the specified key.
❖ Lists are dynamic. ❖ Tuples are fixed ❖ Sets are dynamic. ❖ dict are dynamic.
size in nature.
❖ Lists are enclosed in ❖ Tuples are ❖ sets are enclosed in ❖ dicts are enclosed
square brackets[ ]. enclosed in curly brace {}. in curly brace{}.
parenthesis().