0% found this document useful (0 votes)
26 views6 pages

IP Notes-Dict

The document provides an overview of dictionaries in Python, highlighting their structure as key-value pairs, mutability, and methods for creation, access, updating, and deletion. It contrasts dictionaries with lists, emphasizing differences in ordering, indexing, and element uniqueness. Additionally, it covers nested dictionaries, membership operators, and common functions and methods associated with dictionaries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views6 pages

IP Notes-Dict

The document provides an overview of dictionaries in Python, highlighting their structure as key-value pairs, mutability, and methods for creation, access, updating, and deletion. It contrasts dictionaries with lists, emphasizing differences in ordering, indexing, and element uniqueness. Additionally, it covers nested dictionaries, membership operators, and common functions and methods associated with dictionaries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

IP notes – Grade 11

Lesson 4 – Working with Lists & Dictionary


DICTIONARY
 A dictionary is a collection of items where each item is stored as a pair: key: value.
 Unlike lists, dictionaries are unordered, and the elements are accessed using keys instead of
index numbers.
 Dictionaries are mutable, meaning you can change, add, or remove elements after the
dictionary is created.
 Dictionaries are defined using curly braces {}.
 Dictionaries are efficient for looking up data based on a unique key.
 Useful for representing structured data, like a database record or a real-life address book.
Features of Dictionaries
• Each key maps to a value and is unique.
• Each key is separated from its value by a colon.
• Items are separated by commas.
• The entire dictionary is enclosed in curly braces.
• It is very useful when storing and retrieving all key value pairs.
• Dictionaries are indexed or arranged on the basis of keys.
• Stored dictionary items can be retrieved very fast by their key.
Difference Between List and Dictionary:
List Dictionary
An ordered collection of A collection of key-value pairs
elements/items.
Syntax: [item1, item2, item3] Syntax: {key1: value1, key2: value2}
Access elements by index Access values by using keys
(list[index]). (dict[key]).
Allows duplicate elements. Keys must be unique (no duplicates
allowed).
Iterate directly over elements. Iterate over keys, values, or key-value
pairs.
Eg: fruits = ["apple", "banana", Eg: student = {"name": "Anshita",
"cherry"] "age": 17}

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")

You might also like