Lecture 18 Dictionaries in Python
Lecture 18 Dictionaries in Python
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’]}
>>>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’]}
>>>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
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’]}
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.
>>>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’]}
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?