Lect-04 Dictonaries
Lect-04 Dictonaries
Dr.Harish D. Gadade
Dictionaries in Python
● Creating Dictionary
● Traversing a Dictionary
● Methods in Dictionary
2
Prof. Harish D. Gadade, COEP Technological University, Pune
Creating Dictionaries
● Dictionaries are used to store data values in key:value pairs.
x={1:”Ahaan”,2:”Vihaan”,3:”Ayaan”}
print(x)
● Output
{1:”Ahaan”,2:”Vihaan”,3:”Ayaan”}
3
Prof. Harish D. Gadade, COEP Technological University, Pune
Creating Dictionaries
phonebook={”Ahaan”:”9225518494”,”Vihaan”:”7276861849”}
print(phonebook)
countryCode={“India”:”+91”,”USA”:”+1”}
print(countryCode)
4
Prof. Harish D. Gadade, COEP Technological University, Pune
Accessing Dictionary items
● You can access the items of a dictionary by referring to its key name,
inside square brackets:
x={1:”Ahaan”,2:”Vihaan”,3:”Ayaan”}
print(x[2])
Output
Vihaan
● There is also a method called get() that will give you the same
result:
y=x.get(2)
5
Prof. Harish D. Gadade, COEP Technological University, Pune
Changing Item in Dictionary
● You can change the value of a specific item by referring to its key
name:
x={1:”Ahaan”,2:”Vihaan”,3:”Ayaan”}
x[2]=10
Output
{1:”Ahaan”,2:10,3:”Ayaan”}
6
Prof. Harish D. Gadade, COEP Technological University, Pune
Adding Item in Dictionary
● Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
x={1:”Ahaan”,2:”Vihaan”,3:”Ayaan”}
x[“color”]=”Red”
print(x)
Output
{1:”Ahaan”,2:10,3:”Ayaan”,”color”:”red”}
7
Prof. Harish D. Gadade, COEP Technological University, Pune
Remove Item from Dictionary
● There are several methods to remove items from a dictionary
○ The pop() method removes the item with the specified key name
x={1:”Ahaan”,2:”Vihaan”,3:”Ayaan”}
x.pop(2)
print(x)
Output
{1:”Ahaan”,3:”Ayaan”}
● Del operator is also used to delete key and its associated value. If a
key is in dictionary then it will be removed otherwise Python raise an
error.
Del dictionary_name[key]
8
Prof. Harish D. Gadade, COEP Technological University, Pune
Traversing Dictionary
● The for loop is used to traverse all the keys and values of a
dictionary. A variable of the for loop is bound to each key in an
unspecified order. It means it retrieves the key and its value in any
order.
grades={"Ahaan":"A","Vihaan":"B","RItuja":"C"}
{'Ahaan': 'A', 'Vihaan': 'B', 'RItuja': 'C'}
print(grades)
Ahaan : A
Vihaan : B
for key in grades:
RItuja : C
print(key,":",grades[key])
9
Prof. Harish D. Gadade, COEP Technological University, Pune
Methods in Dictionary
1. keys() grades={"Ahaan":"A","Vihaan":"B","RItuja":"C"}
2. values() a=grades.keys()
3. items() print(a)
4. get(key) print(grades.values())
5. pop(key) print(grades.items())
print(grades.get("Ahaan"))
grades.pop("Vihaan")
print(grades)
dict_keys(['Ahaan', 'Vihaan', 'Rituja'])
dict_values(['A', 'B', 'C'])
dict_items([('Ahaan', 'A'), ('Vihaan', 'B'),
('Rituja', 'C')])
A
{'Ahaan': 'A', 'Rituja': 'C'}
10
Prof. Harish D. Gadade, COEP Technological University, Pune