0% found this document useful (0 votes)
28 views

9 Notes Dictionary

The document discusses Python dictionaries including how to create, access, update and delete elements from dictionaries. It provides examples of creating dictionaries using literal notation and the dict() function. It also covers dictionary methods like keys(), values(), items(), get(), update(), clear(), del() and pop().

Uploaded by

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

9 Notes Dictionary

The document discusses Python dictionaries including how to create, access, update and delete elements from dictionaries. It provides examples of creating dictionaries using literal notation and the dict() function. It also covers dictionary methods like keys(), values(), items(), get(), update(), clear(), del() and pop().

Uploaded by

Neha Parmanandka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

IP CBSE Syllabus

Dictionary: concept of key-value pair, creating, initializing, traversing, updating and


deleting elements, dictionary methods and built-in functions: len(), dict(), keys(),
values(), items(), get(), update(), clear(), del()

• Python dictionary is an unordered collection of items.


• A dictionary has a key : value pair.
• A dictionary doesn’t have an index like in Lists. In Lists, we used to remember
the index, in Dictionary we deal with key. There is no index.
• We use curly bracket for dictionaries and in a dictionary, key and values are
stored in pairs.
Let us see an example,

Key Value
"ELENA JOSE" 450
Marks "PARAS GUPTA" 467
"JOEFFIN JOSEPH" 480

Here,
- Key PARAS GUPTA with a value 467
- Key ELENA JOSE with a value 450
- Key JOEFFIN JOSEPH with a value 480

Creating Dictionary

A dictionary can be created in three different ways :


Dictionary using literal notation.
Method 1:
To declare a dictionary, the syntax is:
directory-name = {key : value, key : value,.............. , keyN : valueN}
➢ Dictionary is listed in curly brackets, inside these curly brackets ( { } ), keys and
values are declared. You remember List has square brackets.
➢ Each key is separated from its value by a colon (:) while each element is
separated by commas.
➢ The keys in a dictionary must be immutable type like strings or numbers.
➢ Dictionary keys are case sensitive.
➢ The values in the dictionary can be of any type.

EXAMPLE 1:
For example, let us create and print the Marks dictionary:
>>> Marks = {"ELENA JOSE" : 450, "PARAS GUPTA" : 467, "JOEFFIN JOSEPH" : 480}

Here ELENA JOSE is the key and its value is 450, PARAS GUPTA is the key and its value is 467.

>>> print (Marks) #this will print Dictionary named Marks


Output:
{'ELENA JOSE': 450, 'PARAS GUPTA': 467, 'JOEFFIN JOSEPH': 480}

EXAMPLE 2:

teachers={“BHAWNA”:”Math”, “HARMEET ”:”Physics”, ”MEENAL”:”Chemistry”}


# in the above example, key is also in quotes and value is also in quotes.

EXAMPLE 3:
Similarly, let us create another dictionary called Student with following key : value pairs:
>>> Student = { "Name" : "Surbhi Gupta",
"Rollno" : 11,
"Address" : "F444 - MIG Flat, Sec-7, Rohini",
"Phone" : "7286798500"
}
>>> print (Student)
{'Name': 'Surbhi Gupta' , 'Rollno': 11 , 'Address': 'F2/27 - MIG Flat, Sec-7, Rohini' , 'Phone':
'7286798500'}

Example 4 : You make a dictionary of your friends names and phone numbers.
Friends name will be a key, phone number will be a value.

Method 2 of Creating Dictionary

2. Dictionary using dict() function.


The dict( ) function is used to create a new dictionary with no items. For
example,
>>> weekdays = dict(Sunday=0, Monday=1, Tuesday=2, Wednesday=3)
(weekdays is the name of dictionary here)
>>> print (weekdays)
Output:
{'Sunday': 0, 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3}
(Python has automatically made it as a dictionary)

Creating empty dictionary using {}.


An empty dictionary can be created using {}.

Accessing Elements of Dictionary


teachers={“BHAWNA”:”Math”, “HARMEET ”:”Physics”, ”MEENAL”:”Chemistry”}
>>>teachers[“BHAWNA”]
“Math” will be the output

print(teachers[“HARMEET”])
Will print Physics

Traversing the Dictionary


• We use for loop to traverse the dictionary
Example 1:

teachers={"BHAWNA":"Math", "HARMEET":"Physics", "MEENAL":"Chemistry"}

for i in teachers:
print(i, teachers[i])

Output:
BHAWNA Math
HARMEET Physics
MEENAL Chemistry

Traversing the following:


Marks = {"ELENA JOSE" : 450, "PARAS GUPTA" : 467, "JOEFFIN JOSEPH" : 480}

for i in Marks:
print(i, Marks[i])
Output:
ELENA JOSE : 450
PARAS GUPTA: 467,
JOEFFIN JOSEPH : 480
Using keys() and values() function
• keys() function displays only the keys of the dictionary
• values() function displays only the values of the dictionary

teachers={"BHAWNA":"Math", "HARMEET":"Physics", "MEENAL":"Chemistry"}


print(teachers.keys())
print(teachers.values())

Output:
dict_keys(['BHAWNA', 'HARMEET', 'MEENAL'])
dict_values(['Math', 'Physics', 'Chemistry'])

Points to Remember about Dictionary


1) Dictionary is not an ordered set. Ordering is like in the case of indexes-
0,1,2 and so on. Like in Example above Elena Jose, Paras Gupta have no
sequence.
2) Dictionary is not a sequence like Lists, tuple
3) Dictionary has pairs- keys, values
4) Keys have to be immutable. Strings and number
5) Keys have to be unique? (Think why) Because keys are used to identify
values. In teachers[“BHAWNA”], “BHAWNA” is unique as it has to return
a value : Math

teachers={"BHAWNA":"Math", "BHAWNA":"Phy",
"MEENAL":"Chemistry"}
# This is erroneous because Key BHAWNA is NOT unique.
print(teachers)
# It will consider only this as dictionary :
{'BHAWNA': 'Phy', 'MEENAL': 'Chemistry'}

6) Values can be same. Example two teachers can have the same value :
Math
Example : BHAWNA and HARMEET both values Math here:

teachers={"BHAWNA":"Math", "HARMEET":"Math", "MEENAL":"Chemistry"}


print(teachers)

Adding pair in a Dictionary


teachers={"BHAWNA":"Math", "HARMEET":"Physics", "MEENAL":"Chemistry"}
teachers["NANCY SEHGAL"]= "Comp Sc"
print(teachers)
Output:
{'BHAWNA': 'Math', 'HARMEET': 'Physics', 'MEENAL': 'Chemistry', 'NANCY
SEHGAL': 'Comp Sc'}
In the Dictionary named Marks , we will add item:
Marks["Gagan Singh"]= 650
Now Dictionary will be like this :
Marks = {"ELENA JOSE" : 450, "PARAS GUPTA" : 467, "JOEFFIN JOSEPH" : 480, “Gagan Singh”:650}
• So we have noted that as Dictionaries are Mutable, Pairs can be added to it.

Changing values in a Dictionary

teachers["BHAWNA"]= "Math Comp Sc"


Now print(teachers) will print
{'BHAWNA': 'Math Comp Sc', 'HARMEET': 'Physics', 'MEENAL': 'Chemistry',
'NANCY SEHGAL': 'Comp Sc'}

• So we have noted that as Dictionaries are Mutable, Value can be changed for a pair.

Deleting elements in a Dictionary

• We use del fuction with key to delete an item.


teachers={"BHAWNA":"Math", "HARMEET":"Physics", "MEENAL":"Chemistry"}

del(teachers["MEENAL"])
print(teachers)
(Meenal:Chemistry pair is deleted

Output:
{'BHAWNA': 'Math', 'HARMEET': 'Physics'}

Note : As we write del and then (, same way we write len function :
print(len(teachers))

• We can also use pop function with key to delete an item.

teachers={"BHAWNA":"Math", "HARMEET":"Physics", "MEENAL":"Chemistry"}


teachers.pop("MEENAL")
print(teachers)

Functions used in Dictionary

teachers={"BHAWNA":"Math", "HARMEET":"Physics", "MEENAL":"Chemistry"}


Function/Method Usage Output
len(): print(len(teachers)) 3
Returns number
of pairs.
get(): print(teachers.get("HARMEET")) Physics
Returns the
value of the
specified key
get(): print(teachers.get("Seema")) None
if we write a
key that has no
value, none is
returned.
keys(): print(teachers.keys()) dict_keys(['BHAWNA',
Returns a list 'HARMEET', 'MEENAL'])
containing the
dictionary's keys
values(): print(teachers.values()) dict_values(['Math',
'Physics',
Returns a list of 'Chemistry'])
all the values in
the dictionary
copy() x will be dictionary
same as teachers
Creates a copy x = teachers.copy()
of dictionary
print(x)
clear(): {}
x.clear()
Removes all
elements
pop() teachers.pop(“HARMEET”) {"BHAWNA":"Math", "ME
removes the ENAL":"Chemistry"}
pair with
HARMEET as
key
dict_items([('BHAWNA'
items() teachers={"BHAWNA":"Math", , 'Math'),
"HARMEET":"Physics", ('HARMEET',
prints keys and "MEENAL":"Chemistry"} 'Physics'),
values in ('MEENAL',
dictionary in a print(teachers.items()) 'Chemistry')])
list
update() teachers={"BHAWNA":"Math", {'BHAWNA': 'Math',
"HARMEET":"Physics", 'MEENAL':
it adds the pair "MEENAL":"Chemistry"} 'Chemistry', 'Amita':
in the 'English'}
dictionary {'MEENAL':
teachers.update({"Amita":"English"}) 'Chemistry', 'Amita':
Observe that 'English'}
pair is supplied
in the form of
dictionary.

Difference between del and pop to delete a pair :


teachers={"BHAWNA":"Math", "HARMEET":"Physics",
"MEENAL":"Chemistry"}

teachers={"BHAWNA":"Math", "HARMEET":"Physics", "MEENAL":"Chemistry"}


print("using pop")

x=teachers.pop("HARMEET") # x will be assigned Physics

y=del(teachers["BHAWNA"]) # will give Error


print(y)
• Use d.pop if you want to capture the removed value, like
item = teachers .pop("Harmeet").
• Use del if you simply want to delete an item from a dictionary.

Answer the following:


Define:
(i) A dictionary with 5 fruit names as keys and their respective prices as values.
Ans: {'banana':70,'mango':60,'apple':120,'peach':120,'grapes':100)

(ii) A dictionary with 3 student names as keys and their aggregate marks
percentages as respective values.
Ans : {'Amar’:80, 'Akbar':78.5, 'Anthony':80.6}

(iii) A dictionary named student with the following elements:


a. admno:admission number of the student (string)
b. name:name of the student (string)
c. dob: Date of birth of the student (string)
d. class: Class of the student (integer)
Ans: Student={'admno': '12332', 'name': 'Rohan', 'dob': '12/10/2006', 'class':8}

(iv) A dictionary named item with the following elements:


a. code:item code(integer)
b. name:name of the item (string)
c. price: price of the item (floating point)
d. qty: balance quantity of the item in stock (floating point)
Ans: item={'code':233, 'name': 'Soap', 'price': 28.50, 'qty':8.0}
(v) A dictionary named mobile with the following elements:
a. make:Name of the brand (Apple, Samsung, etc.)
b. model: Model name (iPhone X, Note 9, etc.)
c. year: Year of launch (integer)
d. price: Price in INR (integer)
Ans: mobile={'make':233, 'model': ' iPhone 11 Pro', 'year':2019,'price':115000}
(vi) A dictionary Eng2Lang with 5 elements, where key is an English language word
and value is the corresponding word in your mother tongue.
(vii) A dictionary to store the vertices of a polygon. Each element of the dictionary
should have a vertex name as the key and a tuple to store the coordinates of
the vertex as its value. For example, an element of the dictionary may be
‘A’:(2,3)
2. Consider dictionary D given below:
D={'U1':'Programming', 'U2':'Data structures', 'U3':'Files',
'U4':'RDBMS', 'U5':'Networks'}
With reference to D, state True/False for each of the following expressions:
(i) 'U2' in D (ii) U2 in D (iii) 'Programming' in D
(iv) Programming in 'D' (v) 'U3' not in D (vi) 'Files' not in D

.
(i) True (ii) False (iii) (iv) False
False
(v) (vi) True
False

Q) Consider dictionary weight given below and write the output :


weight= {'A1':8,'A2':7,'B1':6,'B2':5,'C1':4,'C2':3,'D1':2,'D2':1,'E':0}
(i) for k in weight:
print(k,"-",weight[k])
(ii) for k in weight.keys():
print(k,"-",weight[k])
(iii) for k in weight.values():
print(k, end=' ')
(iv) for k,v in weight.items():
print(k,"-",v)

Ans:

(i) A1 - 8 (ii) A1 - 8 (iii) 8 7 6 5 4 3 2 1 0 (iv) A1 - 8


A2 - 7 A2 - 7 A2 - 7
B1 - 6 B1 - 6 B1 - 6
B2 - 5 B2 - 5 B2 - 5
C1 - 4 C1 - 4 C1 - 4
C2 - 3 C2 - 3 C2 - 3
D1 - 2 D1 - 2 D1 - 2
D2 - 1 D2 - 1 D2 - 1
E - 0 E - 0 E – 0

Programs
Write a program to accept a key from the user and remove that key from the dictionary if
present.

Solution :
d1 = {1 : 25, 2 : 90, 3 : 50}
k=int(input(“Enter any key”))
if k in d1:
d1.pop(k)
print(d1)# dictionary will be displayed without the value that is deleted
else:
print(“Key not found”)

Q. Write a program to count the number of elements(pairs) in a


dictionary.

Solution:
d1={1:”Aman”,2:”Suman”,3:”Aman”,4:”Kranti”,5:”Suman”}
print(len(d1))

Q3. Accept a key from the user and modify it’s value.

Solution:

d1={1:”Aman”,2:”Suman”,3:”Aman”,4:”Kranti”,5:”Suman”}

k=int(input(“Enter the key”))

v=input(“Enter the modified value”)

d1[k]=v

print(d1)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy