You are on page 1of 22

PYTHON Programming (CST310)

Lecture 18: Dictionaries in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
October 10, 2023
Dictionaries Data-type in Python
• Dictionary is another datatype in Python, which is similar to a list in
that it is a collection of elements (objects).
• In Lists, the index positions are integers only. But in Dictionaries, the
indices can be (almost) any type.
• In Dictionaries in python, the items are stored as key-value pair inside
the curly braces.
student= {key:value, key2:value2, key3:value3}
• We can think Dictionaries as a mapping between set of indices (which
are keys) and set of values.
• Each key maps to a value.
• The association of a key and a value is called as key-value pair.
How to Create a Dictionary
The elements in dictionaries in python are enclosed inside the Curly Braces {}.
student= {key:value, key2:value2, key3:value3}
>>> student = {"name":“lokit", 'age’:21, "courses":['python', ‘Database’]}

In Lists, elements are enclosed inside the Square Brackets []


In Dictionaries, elements are enclosed inside the Curly Braces {}
Empty Dictionary
Dictionary with no elements is called as Empty Dictionary.
Empty Dictionary can be created as : empty= {}
The function dict also creates a new dictionary with no items.
>>>d= dict()
>>>print(d)
>>>{}
So, dict() will create a empty dictionary (dictionary with no items).
The curly brackets, {}, represent an empty dictionary
Accessing Elements of the Dictionary
>>> student = {"name":“lokit", 'age’:21, "courses":['python', ‘Database’]}

To access the elements (key-value pairs) of a dictionary, use the following


syntax:
student[key]

For example,
>>> student[‘name’]
>>> student[‘age’]
Keys in Dictionaries
a={ 123:[1,2,3] }
b= { [1,2]:'b’ } # Output?
Keys in Dictionaries
a={ 123:[1,2,3] }
b= { [1,2]:'b’ } # Output?

In Python, dictionaries are implemented as hash tables, which means that they require
their keys to be hashable.
A key is hashable if it has a hash value that never changes during its lifetime and can be
compared to other objects.
Lists in Python are mutable, meaning they can be changed after they are created. Since
lists are mutable, they are unhashable, and therefore, they cannot be used as keys in
dictionaries.
Use immutable data types (such as strings, numbers, or tuples) as keys in your
dictionary.
Accessing all Keys of a Dictionary
>>> student = {"name":“lokit", 'age’:21, "courses":['python', ‘Database’]}

To access all the keys of a dictionary, use the key() method:

>>>student.keys()
dict_keys(['name', 'age', 'courses’]) #this will be the output
Accessing all Values of a Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

To access all the values of a dictionary, use the values() method:

>>>student.values()
dict_values(['rahul', 23, ['python', 'Operating System’]]) #output
Accessing all Elements (Key-Value) of a
Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

To access all the items (key-value pairs) of a dictionary, use the items() method:

>>>student.items()
dict_items([('name', 'rahul'), ('age', 23), ('courses', ['python’, Database'])
Accessing Items of a Dictionary using Loops
All the Elements(key-value) of a Dictionary can also be accessed using loops.
>>>student={"name":“lokit", 'age’:21, "courses":['python', ‘Database’]}

for key in student: #Python iterates over the keys of the dictionary student
print(key) # we will get only the keys of the dictionary
or
for keys in student.keys():
print(keys) # this will print all the keys

for values in student.values():


print(values) # this will print all the values
or
for key in student:
print(student[key])

for items in student.items():


print(items) #this will print all the elements (key-values pairs)
Accessing Non-Existing Key of a Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

Suppose in above defined dictionary, we try to access key index which does not
exist:
print(student[‘city’]) # Interpreter will give error
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
print(student['city’])
KeyError: 'city
Accessing Non-Existing Key of a Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

We know on accessing non-existing key of a dictionary, python gives error.

Suppose, we don’t want to get the error for non-existing key, we will use the
get() method.
print(student.get(‘city’)) # this will return none, if key doesn’t exist.

If we want to have some custom message for non-existing key:


print(student.get(‘city’, ‘KEY Not Found’))
Adding new Items (Key-Value) to an Existing Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

>>>student[‘city’]=‘Srinagar’
# This will insert the item with key city and value Srinagar in the dictionary
student
# If key ‘city’ is already there in the dictionary, then it will update the value of
existing key ‘city’

print(student)
{'name': 'rahul', 'age': 23, 'courses': ['python', 'Operating System'], 'city’: Srinagar'}
Method 2:
Adding/updating new Items (Key-Value) to an Existing
Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

Suppose, we want to do following tasks in above dictionary:


1. Updation of ‘Rahul’ to ‘Lokit’
2. Updation of age 23 to 21
3. Insertion of new item (key-value) City:Srinagar
Method 2:
Adding/updating new Items (Key-Value) to an Existing
Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

Suppose, we want to do following tasks in above dictionary:


1. Updation of ‘Rahul’ to ‘Lokit’
2. Updation of age 23 to 21
3. Insertion of new item (key-value) City:Srinagar

One way is
Student[‘name’]=‘Sada’
student[‘age’]=22
student[‘city’]=‘Srinagar’

If We want to do the above 3 tasks in one statement, we will use the update() method.
student.update({‘name’:’Sada’, ‘age’:22, ‘city’: ‘Srinagar’})
Deletion in Dictionaries
Deletion of items in dictionaries can be done by following ways:
1. Using del
del student[‘city’]
2. Using pop method
student.pop(‘city’)
pop method returns the value it has deleted.
Dictionaries in Python are Mutable
• Like Lists, the dictionaries in python are mutable in nature.
• So, updation in the same object of dictionaries are allowed.
Methods/Functions in Dictionaries
• len(): Counting keys of a dictionary.
• Copy() method: this method creates a copy of elements of a
dictionary
Output?
student = {"name":"rahul", 'age':23, “name”: ”Arjun” }
Output?
Can we do This?

student = {[‘’fname’’, ‘’lname”]: “NIT Srinagar" } #list is used as a key

student = {(‘’fname’’, ‘’lname”]): “NIT Srinagar" } #tuple is used as a key


Only Immutable objects can be used as a key
Since lists are mutable, we can't use a list as a key in a dictionary.
This is because only an immutable object can be used as a key in a dictionary.
Thus, we can use tuples as dictionary keys if needed

You might also like