0% found this document useful (0 votes)
116 views30 pages

DICTIONARIES

Here are 3 sample programs using dictionaries: 1. Phone book: phone_book = {'John': 938477566, 'Patel': 987456321, 'David': 978522338, 'Sara': 944455874, 'Tom': 782233699} print(phone_book) phone = input("Enter a name to search phone number: ") print(phone_book.get(phone, "Name not found")) 2. Student marks: marks = {'John': 85, 'David': 79, 'Sara': 74, 'Tom': 68, 'Jenny': 90} for name, mark in marks.items(): if

Uploaded by

FootlooseFùtbol
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)
116 views30 pages

DICTIONARIES

Here are 3 sample programs using dictionaries: 1. Phone book: phone_book = {'John': 938477566, 'Patel': 987456321, 'David': 978522338, 'Sara': 944455874, 'Tom': 782233699} print(phone_book) phone = input("Enter a name to search phone number: ") print(phone_book.get(phone, "Name not found")) 2. Student marks: marks = {'John': 85, 'David': 79, 'Sara': 74, 'Tom': 68, 'Jenny': 90} for name, mark in marks.items(): if

Uploaded by

FootlooseFùtbol
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

Chapter 13

 Dictionaries are another type of collection in Python but with a twist,


instead of having an index associated with each data item,
dictionaries have a key and a value of that key
 Python dictionaries are a collection of some key-value pairs

 Creating a Dictionary
 To create a dictionary you need to include the key:value pairs in
curly braces as per the following syntax
<dict_name>={<key>:<value>,
<key>:<value>,
<key>:<value>}
Notice that
• The curly bracket mark the beginning and end of the dictionary
• Each entry (key:value) consist of a pair separated by colon
• The key:value pairs are separated by comma’s (,)
Eg :
teacher={"maths":"Maheshwari",
"English":"Libymon",
"Computer":"Babitha",
"Physics":"Sinda",
"Chemistry":"Rajam"}
print(teacher)
 Elements of a dictionary can be accessed only using the key value
 To access the value we can type as
 for x in teachers :
print(x)
To access the value we can type as teachers[x]
 The keys of a dictionary must be immutable such as string, number, tuple (cannot
be changed)
 If you try to give a mutable type as key, python will give you an error as
“unhashable type”
 Unordered set
 Not a sequence
 Indexed by keys and not by numbers
 Keys must be unique
 We can change the value of the a certain key using the assignment statement as
per the syntax:
 <dictionary>[<key>]=<value>
 To access all the keys in a dictionary at one go, you may use <dictionary>.keys()
 To access all the values in a dictionary at one go, you may use
<dictionary>.values()
1. Initializing a Dictionary
Emp={‘name’:’John’, \
‘age’:32,\
‘salary’:50000}
a) by giving dictionary content in empty { }
D={ }
b) by using dictionary method
D=dict()
Once its declared you can add the values as
<dictionary>[<key>]=<value>
D[“Maths”]=“Ms Maheswari”
a) Specify the key:value pair as keyword argument to
dict( ) function eg
emp = dict ( name =‘John’, age=32, salary =50000)
print(emp)
output:
{'name': 'John', 'age': 32, 'salary': 50000}
b) specify comma- separated key:value pairs:
emp = dict({'name': 'John', 'age': 32, 'salary': 50000})

or without using dict function


emp = {'name': 'John', 'age': 32, 'salary': 50000}
c) Specifying keys separately and values separately :

emp = dict(zip((‘name’,’age’,’salary’),(‘John’,32,’50000)))

The zip function separates all the keys and the values,
the values will be assigned to the corresponding keys
specified in the order.
The key being added must not exist in
dictionary and must be unique
 There are two methods for deleting elements from a
dictionary
i) use the del command :
del <dictionary> [<key>]
eg
del emp[‘age’]
If the key you want to delete is not present in the dictionary
python will give you an error
ii) using the pop( ) method : It will remove the key : value pair but also will
return the value that will be popped
syntax is
<dictionary>.pop(<key>,<in case of error show me>)
eg
[Link](“age”) # will return 32
[Link](“new”,”Not found”)
# will print not found as new key is not present
 Membership operators i.e in and not in will work with Dictionary as well.
 <key> in <dictionary>
 <key> not in <dictionary>
 The in operator will return True if the given key is present in the dictionary
otherwise Fasle
 The not in operator will return True if the given key is not present in the dictionary
otherwise False
Note: The operator in and not in will not apply on values of a dictionary.
1. The len() method :
This method returns the length of the dictionary ie it
will count the elements (key:value pairs)
Syntax : len(<dictionary>)
emp = {'name': 'John', 'age': 32, 'salary': 50000}
print(len(emp))

Output
3
2. The clear( ) method
This method will remove all the items from the
dictionary and makes the dictionary an empty
dictionary.
Syntax
<dictionary>.clear() # takes no arguments and
returns no value
3. The get () method :
It will return the item with the given key similar to
dictionary[key]. If the key is not present then it will give an
error message
Syntax:
<dictionary>.get(key,[default])
Eg :

emp = {'name': 'John', 'age': 32, 'salary': 50000}


[Link](‘name’,”Not present”) # output is John
[Link](‘gender’,” Not present”) # output is Not present
4. The items( ) method :
This will return all the items in the list as key:value
pair tuple. They are returned in no particular order
Syntax : <dictionary>.items()
emp = {'name': 'John', 'age': 32, 'salary': 50000}
seq=[Link]()
for x in seq:
print(x)
5. The update( ) method:
This method merges the key:value pairs from the new
dictionary into the original dictionary, adding or replacing
as needed. The items in the new dictionary are added to the
old one and override any items already there with the same
keys
For eg:
Emp1={'name': 'John', 'age': 32, 'salary': 50000}
Emp2 = {'name': ‘Savitha',’dept’=‘sales’, 'age': 27}
[Link](Emp2)
print(Emp1)
Output:
{'name': ‘Savitha',’dept’:‘sales’, 'age': 27, 'salary': 50000}
1. To create a phone dictionary of 5 friends name and phone number .
Print the Dictionary in the sequence and also search for a
particular name and print its phone number.
2. Enter a dictionary of 5 students and their mark and print only the
name of the student who got more than 75 marks
3. Enter a dictionary of 5 students and their mark and print only the
name of the student who lowest mark
4. To create a Dictionary containing names of competition winner as
keys and number of their wins as values : Create a menu driven
program to print the following when the following number is
pressed
1. To display the name of the students which starts with ‘A’ or ‘T’
2. To display the students name with least wins
3. To update the wins of a student entered by the user
4. exit the program
5. Accept a string (A sentence) and count the frequency of the words and
create a dictionary out of it
Eg : word = “This is a super idea This idea will change the idea of learning”
Output = { This : 2,
is : 1,
a :1 ,
super :1,
idea:3 ,
will : 1,
idea
……………………………. }

You might also like