IP Notes-Dict
IP Notes-Dict
1
Creating Dictionaries
A Dictionary can be created in three different ways:
1. Creating an Empty Dictionary
# Using curly braces
my_dict = {}
# Using the dict() method
my_dict = dict()
2. Using Curly Braces
You can directly create a dictionary using curly braces {}:
my_dict = {'name': 'Anshita', 'age': 17, 'grade': 11}
3. Using the dict() Constructor
The dict() function can also be used to create a dictionary:
my_dict = dict(name='Anshita', age=17, grade=11)
Accessing the elements
• To access the elements, you can use the square brackets along with the key to obtain its value.
• An error is received if we try to access data with a wrong key.
months = { 1 : "January", 2 : "February", 3 : "March", 4 : "April", 5 : "May", 6 : "June"}
print (“months[2]: ", months[2])
print (“months[4]: ", months[4])
Output:
months[2]: February
months[4]: April
>>> months[9]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
months[9]
KeyError: 9
Adding values in a dictionary
• We can add new elements to the existing dictionary, extend it with single pair of values or join
2 dictionaries into one.
• To add only one element to the dictionary, use this method.
Dictionary_name [key] = value
Example-
d= {'Name': 'Amy', 'Age': 7, 'Class': 'First'}
d[‘Mobile'] = 7412583; # update existing entry
print (d)
Output: {'Name': 'Amy', 'Age': 7, 'Class': 'First', 'Mobile': 7412583}
2
Updating elements in a dictionary
• Updating is the process of modifying the existing value.
Syntax: <dictionary>[<key>] = <value>
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1
{'brand': 'mrcet', 'model': 'college', 'year': 2004}
• If the key does not exist in the dictionary, then it will add the key value pair in the dictionary.
>>> dict1[‘color]='blue'
>>> dict1 - O/p- {'brand': 'mrcet', 'model': 'college', 'year': 2004,’ color’: ‘blue’}
Any 2 dictionaries can be merged into one using update() method.
• It merges the keys and values of a dictionary into another and overwrites the values of the
same key.
Syntax- Dictionary1.update(Dictionary2)
one = {'name': 'Mohan Kumar', 'age': 35, 'city': 'New Delhi'}
two = {'age': 32, 'country': 'India'}
one.update(two)
print(one)
O/p - {'name': 'Mohan Kumar', 'age': 32, 'city': 'New Delhi', 'country': 'India'}
Keys() and values()
• The keys() method returns the keys of the dictionary, as a list.
Syntax - dictionary.keys()
• The values() method returns the values of the dictionary, as a list.
Syntax - dictionary.values()
Example
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(car.keys())
print(car.values())
print(car.items())
Output:
dict_keys(['brand', 'model', 'year'])
dict_values(['Ford', 'Mustang', 1964])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries.
myfamily = {"child1" :{"name" : "Emil", "year" : 2004}, "child2":{"name" : "Tobias", "year" :
2007 }, "child3":{"name" : "Linus", "year" : 2011} }
3
Membership operator in a Dictionary
The “in” operator checks if a particular key is there in the dictionary. If so returns true else false.
student_marks = {'Aman': 85, 'Ravi': 90, 'Priya': 78}
print('Aman' in student_marks) # Output: True
print('John' in student_marks) # Output: False
print('Priya' not in student_marks) # Output: False
Deleting Element
We can remove an item from the existing dictionary by using del command or using pop()
1. Using del command - The keyword del is used to delete the key present in the dictionary. If the
key is not found, then it raises an error.
del <dict>[key]
d ={'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}
del d["tuple"]
print(d)
O/p: {'list': 'mutable', 'dictionary': 'mutable'}
2. Using pop() method –
• Pop method removes the given item from the dictionary.
• It returns the deleted value.<dict>.pop(key)
d ={'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}
d.pop("tuple")
print(d)
O/p: {'list': 'mutable', 'dictionary': 'mutable'}
3. popitem()- It returns and removes the last inserted item from dictionary
<dict>.popitem()
d ={'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}
d.popitem()
print(d)
O/P: {'list': 'mutable', 'tuple': 'immutable'}
Traversing a dictionary:
Traversing means accessing each element of a dictionary. It is done by using a for loop.
x = {1:1, 2:4, 3:9, 4:16, 5:25}
for key in x:
print(key, x[key])
print('*************************')
for key,value in x.items():
print(key, ':',value)
4
O/p:
11
24
39
4 16
5 25
*********
1:1
2:4
3:9
4 : 16
5 : 25
Common Dictionary Functions & Methods
1. len() – It returns the number of key-value pairs.
Eg:- d1 = {1:10, 2:20, 3:30, 4:40}
len(d1) O/p - 4
2. get() – It returns a value for the given key. If the key is not available, then it returns None.
Eg:- d1={‘sun’:’Sunday’ , ‘mon’:’Monday’, ‘tue’:’Tuesday’, ‘wed’ :’Wednesday’, ‘thu’ :
‘Thursday’ }
d1.get(‘mon’) → ‘Monday’
d1.get(5) → None
d1.get(6,'never') → 'never‘
3. str(dict) – Return a printable string representation of a dictionary.
>>> d1 = {1:10, 2:20, 3:30, 4:40}
>>> str(d1) O/p - '{1: 10, 2: 20, 3: 30, 4: 40}‘
4. items() – Returns the items as key and value pair.
Syntax - dictionary.items()
car={"brand":"Ford",”model":"Mustang","year":1964}
print(car.items())
Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
5. clear() - Deletes or clear all the items of the dictionary
>>> xy = {‘a':95,‘b':89,‘c':92, ‘d':85}
>>> xy.clear()
>>> xy
{}
5
Program
#To generate and print a dictionary that contains a number (between 1 and n) in the form (x,
x*x).
n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
Program
To input product names and prices. Display the price of the item that is being searched.
d={}
ch='y'
while ch=='y' or ch=='Y':
name=input("Enter the name of the product : ")
price=eval(input("Enter price :"))
d[name]=price
ch=input("Want to add more items (Y/N) :")
print(d)
z=d.keys()
prod=input("Enter the product to search for :")
for x in z:
if x==prod:
print("Price of " ,x, "is " , d[x])
else:
print("Bye")