Dictionary Notes
Dictionary Notes
Data structure are the structures that hold and organize data or information.
The four main types are lists, tuples, sets and dictionaries.
So Strings, Lists, Tuples are ordered collections of objects. And these data structures
maintain in order.
For example, in set and dictionaries, initial order – the order in which we specified the
elements is not maintained. So Sets and Dictionary are unordered collections of
objects.
An unordered collection/sequence called Dictionary.
Unlike sequence, python collection do not have any order. They are unordered and
unindexed data structures. This means that is not necessary to get the order in which
we insert items.
Python Sequences:
The main purpose of a dictionary is to map unique keys with a value so that retrieving
information is optimized when we know the key.
Dictionaries are mutable and we can simply add a new key-value pair in the dictionary
by assigning them.
Example: Telephone Directory – numbers are stored according their name and
address.
So here,
Name - key
Telephone numbers - value
Dictionary in Python:
{“Python”:”dictionary”}
1. Each key maps to a value. The association of a key and a values is called
a “key-value pair”. There is no defined order for the pairs; thus a
dictionaries are unordered.
2. Each key is separated from its value by a colon (:) and entire dictionary is
closed in curly braces { } example: {“Python” : “Dictionary”}
3. Keys are unique and immutable; Values are mutable and can be changed.
5. The values of a dictionary can be of any type, but the keys must be of
immutable data type such as string, numbers or tuples.
4. Dictionary is mutable. We can be add new items and change the values of
existing items.
KEYS VALUES
1 ONE
2 TWO
3 THREE
CREATING A DICTIONARY:
It is enclosed in curly braces { } and each item is separated from other item by
a comma (,).
Within each item, key and values are separated by a colon (:).
Syntax:
Examples:
KEYS
d= { } #empty dictionary
Output: VALUES
d1={1:'one',2:'two',3:'three',4:'four'}
d2={1:10,2:20,3:30,4:40,5:50}
d3={1:'one', 'two':2, (1,2,3): 'Numbers', 1.5: 'Float'}
print(d1)
print(d2) Note: Dictionary keys are case-sensitive.
print(d3) i.e. same name but different cases of
key will be treated distinctly.
Output
2. To create a dictionary using string data type for both key-value pairs.
d2={'input':'Keyboard','output':'Printer','language':'Python'}
print(d2) Output:
d3=dict() Output:
print(d3) {} Represent an empty dictionary
dict( ) function can also be used to create a copy of dictionary by passing a dictionary
as an argument to dict () function.
a={1:'one',2:'two'} Output:
b=dict(a) {1: 'one', 2: 'two'}
print(b)
{}
d=dict()
print(d)
d[1]="one“
d[2]="two“
d[3]="three“
d[4]="four“
d[5]="five“
print(d) Output:
{}
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
{}
Syntax:
<dictionary_name>[key]
Example: Output:
print("dict1['Name']:", dict1['name'])
{}
TRAVERSING A DICTIONARY:
Traversing a dictionary means accessing each element of a dictionary. This can be
done by using a for loop or a while loop for iterating the dictionary elements.
d={1:'one',2:'two',3:"three",4:"four",5:'five'}
for i in d:
print(i, ":", d[i])
Output:
1 : one
2 : two
3 : three
4 : four
5 : five
{}
TRAVERSING A DICTIONARY:
Write a program to enter names of employees and their salaries as input and store
them in a dictionary. (Using for loop)
Output:
EMPLOYEE_NAME SALARY
Alka 12000
Rajat 15000
Yashu 10000
{}
TRAVERSING A DICTIONARY:
classxi=dict()
n=int(input("Enter total number of sections in xi class: "))
i=1
while i<=n:
a=input("Enter sections:")
b=input("Enter stream name:")
classxi[a]=b
i=i+1
print("class",'\t',"stream name")
for i in classxi:
print("XI",'\t',i,'\t',classxi[i])
{}
Enter sections:
C
OUTPUT:
Enter stream name:
SCIENCE WITH CS
Enter total number of sections in xi class: Enter sections:
5 D
Enter sections: Enter stream name:
A COMMERCE WITH MATHS
Enter stream name: Enter sections:
SCIENCE WITH ECO E
Enter stream name:
Enter sections:
COMMERCE WITH IP
B
class stream name
Enter stream name: XI A SCIENCE WITH ECO
SCIENCE WITH BIO XI B SCIENCE WITH BIO
XI C SCIENCE WITH CS
XI D COMMERCE WITH MATHS
XI E COMMERCE WITH IP
{}
We can add new elements to the existing dictionary, extend it with single pair of
values or join dictionaries into one.
If we want to add only one element to the existing dictionary, the new key-value pair
will be added at the end of the dictionary.
Syntax:
Dictionary_name[key]=value
{}
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday'}
print(d1)
d1['thur']='Thursday' #append new item
print(d1)
Output:
Syntax:
<dictionary_name>[<key>]=<value>
Example:
d1={'Teena':18,'Riya':12,'Alya':22,'Ravi':25}
print(d1)
Output:
d1['Riya']=28
print(d1) {'Teena': 18, 'Riya': 12, 'Alya': 22, 'Ravi': 25}
d1['Priya']=20 {'Teena': 18, 'Riya': 28, 'Alya': 22, 'Ravi': 25}
print(d1) {'Teena': 18, 'Riya': 28, 'Alya': 22, 'Ravi': 25, 'Priya': 20}
{}
Note: While adding a value, if the key value already exists, the value gets updated.
Otherwise, a new key with the value is added at the end of the dictionary.
Update( ) function:
Two dictionaries can be merged into one by using update( ) method. It merges the keys
and values of one dictionary with another and overwrites values of the same key.
Syntax:
dictname.update(dictname2)
{}
Example:
d1={1:10,2:30,3:30,4:40,5:50} Output:
d2={2:20,3:30,6:50} {1: 10, 2: 30, 3: 30, 4: 40, 5: 50}
print(d1) {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 50}
d1.update(d2)
print(d1)
{}
We can remove an item from the existing dictionary by using del command or using
pop ( ) function.
The keyword ‘del’ is used to delete the key present in the dictionary. If the key to be
deleted is not found, then it raises an error.
del dictname[key]
{}
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thur':'Thursday'}
print(d1)
del d1['mon']
print(d1)
Output:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thur':'Thursday'}
print(d1)
del d1['fri']
print(d1)
Output:
Note: If a particular key is not there, then it will return result in KeyError
{}
For example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thur':'Thursday'}
del d1
print(d1) Output:
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(d1)
NameError: name 'd1' is not defined
Pop( ) method will not only delete the item specified by the key from the dictionary
but will also return the deleted value.
Syntax:
dictname.pop(key)
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday'}
d1.pop('wed')
'Wednesday'
print(d1)
{'mon': 'Monday', 'tues': 'Tuesday'}
{}
It returns and removes the last inserted (key, value) pair from the dictionary
Syntax:
dictname.popitem()
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday','sat':'
Saturday'}
d1.popitem()
('sat', 'Saturday')
print(d1)
{'mon': 'Monday', 'tues': 'Tuesday', 'wed': 'Wednesday', 'thurs': 'Thursday', 'fri': 'Friday'}
{}
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
'wed' in d1
True
'sun' in d1
False
'sun' not in d1
True
{}
len()
sorted(
clear() 1. len()
)
2. clear()
3. get()
popite
4. items()
get()
m() 5. keys()
Python 6. value()
Dictionary
Methods
7. copy()
8. from keys()
from
keys()
item() 9. popitem()
10. sorted()
copy() keys()
value()
{}
This method returns the length of key-value pairs in the given dictionary.
Syntax:
len(dictionary_name)
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
len(d1)
6
{}
It removes all items from the particular dictionary and returns an empty dictionary.
Syntax:
dictionary_name.clear()
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.clear()
print(d1)
{}
{}
The get() method returns a value for the given key. If key is not available, then
returns the default value none.
Syntax:
dictionary_name.get(key, default=None)
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.get('wed')
'Wednesday‘
print(d1.get('sun'))
None
{}
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
print(d1.get('sun')) Note: Will return None as key does not exist
None
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.get('sun','never')
'never'
{}
Syntax:
dictionary_name.items()
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.items()
dict_items([('mon', 'Monday'), ('tues', 'Tuesday'), ('wed', 'Wednesday'), ('thurs',
'Thursday'), ('fri', 'Friday'), ('sat', 'Saturday')])
{}
Syntax:
dictionary_name.keys()
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.keys()
dict_keys(['mon', 'tues', 'wed', 'thurs', 'fri', 'sat'])
{}
Syntax:
dictionary_name.values()
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.values()
dict_values(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
{}
6. copy():
We can use built-in function copy() to create a new dictionary object by copying it
but it doesn’t modify the original dictionary
Syntax:
Newdic=olddic.copy()
{}
Assigning a dictionary:
d1={'january':31,'February':28,'March':31}
d2=d1
print(d1)
print(d2)
Output:
d1={'january':31,'February':28,'March':31}
d2=d1
print(d1)
print(d2)
d2['April']=30
print(d2) Output:
print(d1) {'january': 31, 'February': 28, 'March': 31}
{'january': 31, 'February': 28, 'March': 31}
{'january': 31, 'February': 28, 'March': 31, 'April': 30}
{'january': 31, 'February': 28, 'March': 31, 'April': 30}
{}
d1={'january':31,'February':28,'March':31}
d2=d1
print("d1: ",d1) Output:
print("d2: ",d2)
d1: {'january': 31, 'February': 28, 'March': 31}
d3=d1.copy() d2: {'january': 31, 'February': 28, 'March': 31}
print("d3: ",d3) d3: {'january': 31, 'February': 28, 'March': 31}
d1: {'january': 26, 'February': 28, 'March': 31}
d2['january']=26 d2: {'january': 26, 'February': 28, 'March': 31}
print("d1: ",d1) d3: {'january': 31, 'February': 28, 'March': 31}
print("d2: ",d2)
print("d3: ",d3)
{}
Write a python program to input ‘n’ names and phone numbers to store it in a
dictionary and to input any name and to print the phone number of that particular
name.
d={}
n=int(input("Enter the Members Count: "))
for i in range(n):
name=str(input("Enter the Name: "))
phoneno=int(input("Enter the PhoneNo: "))
d[name]=phoneno
print(d)
n=input("Enter the name whose phoneno you want:")
print(n," Phone number is: ",d[n])
{}
Output:
Write a python program to find the number of occurrences of each vowel present in
the inputted string.
Write a python program to find the 2 maximum values in a dictionary D with key-
value pairs as {'A':23,'B':56,'C':29,'D':42,'E':78}
The output should be displayed as:
Two maximum values are:
78
56
d={'A':23,'B':56,'C':29,'D':42,'E':78}
val=[] Output:
v=d.values() Two maximum values are:
for i in v: 78
val.append(i) 56
val.sort()
print(“Two maximum values are:")
print(val[-1])
print(val[-2])
Thank you