Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Data Structure (Dictionary)

1. Lists, sets and dictionaries are mutable while tuples are immutable. 2. Lists use brackets, tuples use parentheses, sets use curly braces and dictionaries use curly braces with keys and values separated by commas. 3. Lists, sets and dictionaries can contain duplicate members but dictionaries do not allow duplicate keys.

Uploaded by

Radha Adhikari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Data Structure (Dictionary)

1. Lists, sets and dictionaries are mutable while tuples are immutable. 2. Lists use brackets, tuples use parentheses, sets use curly braces and dictionaries use curly braces with keys and values separated by commas. 3. Lists, sets and dictionaries can contain duplicate members but dictionaries do not allow duplicate keys.

Uploaded by

Radha Adhikari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Dictionaries:

❖ Dict is a collection which is ordered and changeable.


❖ Values can be duplicated, but key values cannot be duplicated[If a key is duplicated,
the old value will be replaced].
❖ The Dict elements are defined within curly brace { }, and the elements are
separated by commas.
❖ The dict()/{} function is used to create the dictionary.
❖ How to create an empty dict.

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

del variable_name[key value]

❖ 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.

Variable_name[new key value name] = value [#The new key value


should be unique. Otherwise, old value will be replaced. ]

❖ 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}

1 clear() ❖ Remove all elements from the dict. d.clear() #{}

2 copy() ❖ Returns a copy of the dict. d.copy()

3 fromkey() ❖ Returns a dictionary with the specified


keys and value.

4 get() ❖ Returns the value of the specified key. d.get(“name”) #Nima

5 items() ❖ Returns a list containing a tuple for d.items()


each key value pair. #dict_items([('name', 'Nima'),
('Age', 15)])

6 keys() ❖ Returns a list containing the d.keys()


dictionary's keys. #dict_keys(['name', 'Age'])
continue..
SL_No Method Description Example
d={“name”:”Nima”,”Age”:15}

7 pop() ❖ Removes the element with the specified d.pop(“name”) #{“Age”:15}


key.

8 popitem() ❖ Remove the last item from the d.popitem() #{“name”:”karma”}


dictionary.

9 setdefault() ❖ Returns a dictionary with the specified d.setdefault(“name”,”Sangay”)


keys and value. #Nima

10 update() ❖ Updates the dictionary with the d.update(“Gender”:”Male”)


specified key-value pairs. #{“name”:”Nima”,”Age”:15,”Gend
er”:”Male”}

11 values() ❖ Returns a list of all the values in the d.values()


dictionary. #dict_values(['karma', '12',
'Male'])
Activity
1) Write a python code that returns the value of the specified key.

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.

1 #program to display the student’s Biodata


2 biodata = {
3 “Name”: “Jigme Wangmo”,
4 “Class”: “IX”,
5 “Age”: 16
6 “Village”: “pelrithang”
7 }
8 key = input(“Enter a key to display student’s information:”)
9 if key in biodata.keys():
10 print(f’The {key} of the student is {biodata.get(key)}’)
11 else:
21 print(f’Sorry! Entered key is not available’)
Answer 2
2) Write a python code that returns a list containing the dictionary's keys.

1 #program to display the keys


2 biodata = {
3 “Name”: “Jigme Wangmo”,
4 “Class”: “IX”,
5 “Age”: 16
6 “Village”: “Pelrithang”
7 }
8 Keys = []
9 for x in biodata.keys():
10 keys.append(x)
11 print(keys)
Answer 3
3) Write a python code that removes the element with the specified key.
1 #program that removes the element with the specified key
2 biodata = {
3 “Name”: “Jigme Wangmo”,
4 “Class”: “IX”,
5 “Age”: 16
6 “Village”: “Pelrithang”
7 }
8 key = input(“Enter any key:”).lower()
9 if key in biodata.keys():
10 print(f’Remove key is:{biodata.pop(key)}’)
11 print(biodata)
21 else:
22 print(f’Sorry! Entered key is not available’)
Answer 4
4) Write a python code that updates the dictionary with the specified key-value pairs.

1 #program that removes the element with the specified key


2 biodata = {
3 “Name”: “Jigme Wangmo”,
4 “Class”: “IX”,
5 “Age”: 16
6 “Village”: “pelrithang”
7 }
8 key = input(“Enter a key:”).lower()
9 element = input(“Enter an element:”).lower()
10 biodata.update({key:element})
11 print(biodata)
Differences
List Tuple Set dict

❖ List is a mutable ❖ Tuple is a ❖ Set is a mutable ❖ dict is a mutable


immutable

❖ 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().

❖ list() function is ❖ Tuple function is ❖ set() function is ❖ dict() function is


used to create a list. used to create a used to create a set. used to create a
Tuple. dict.

❖ It allows duplicate ❖ It allows duplicate It does not allows ❖ It allows duplicate


members. members. duplicate members values, but it does
not allow
duplicate keys.

You might also like